编写函数求一个字符串长度
时间: 2024-02-07 16:03:42 浏览: 23
好的,以下是 Python 代码实现:
```python
def str_len(s):
"""
求字符串长度
"""
count = 0
for _ in s:
count += 1
return count
```
其中,`s` 为输入的字符串,`count` 为计数器,遍历字符串中的每一个字符,每遍历一次计数器自增 1,最后返回计数器的值即为字符串的长度。
相关问题
c语言编写函数求一个字符串长度
好的,以下是 C 语言的代码实现:
```c
#include <stdio.h>
int str_len(char s[]) {
int count = 0;
while (s[count] != '\0') {
count++;
}
return count;
}
int main() {
char s[] = "Hello, world!";
int len = str_len(s);
printf("The length of string is: %d\n", len);
return 0;
}
```
其中,`s` 为输入的字符串,`count` 为计数器,通过遍历字符串中的每一个字符,并判断是否为字符串结尾的`\0`字符,每遍历一次计数器自增 1,最后返回计数器的值即为字符串的长度。
在 `main` 函数中,我们定义了一个字符串 `s`,并调用 `str_len` 函数求出其长度,并将结果输出到控制台。
编写一个函数求字符串长度
好的,以下是一个求字符串长度的函数实现(使用C语言):
```c
int string_len(char *str) {
int len = 0;
while (*str != '\0') {
len++;
str++;
}
return len;
}
```
使用方法:
```c
char *str = "Hello World";
int len = string_len(str);
printf("字符串长度为:%d\n", len);
```
输出结果:
```
字符串长度为:11
```
希望能够帮到您!