求字符串长度(不使用strlen函数)
时间: 2024-05-16 18:15:46 浏览: 13
可以使用循环遍历字符串的方式来求解字符串长度,具体做法如下:
```c
#include <stdio.h>
int string_len(char *str) {
int len = 0;
while (*str != '\0') {
str++;
len++;
}
return len;
}
int main() {
char str[] = "Hello, world!";
printf("The length of string '%s' is %d.\n", str, string_len(str));
return 0;
}
```
输出结果为:
```
The length of string 'Hello, world!' is 13.
```
在上述代码中,`string_len` 函数使用指针 `str` 遍历字符串中的每个字符,直到遍历到字符串的结束符 `\0` 为止,每遍历一个字符,计数器 `len` 就加 1,最后返回计数器的值即可。
相关问题
调用strlen函数求字符串长度
可以使用strlen函数来计算一个字符串的长度,该函数需要传入一个字符串的指针作为参数,返回字符串的长度(不包括字符串末尾的空字符)。
例如,以下代码演示了如何使用strlen函数计算字符串长度:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
printf("Length of string '%s' is %d\n", str, len);
return 0;
}
```
输出结果为:
```
Length of string 'Hello, World!' is 13
```
C语言strlen求字符串长度
你可以使用C语言中的strlen函数来计算字符串的长度。strlen函数位于string.h头文件中,它接受一个以null结尾的字符串作为参数,并返回字符串的长度(不包括null字符)。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
int length = strlen(str);
printf("字符串的长度为:%d\n", length);
return 0;
}
```
在这个示例中,我们声明了一个名为str的字符数组,并将其初始化为"Hello World"。然后,我们使用strlen函数计算字符串长度,并将结果存储在名为length的整型变量中。最后,我们使用printf函数将字符串的长度打印出来。
当你运行这段代码时,它会输出:
```
字符串的长度为:11
```
这表明字符串"Hello World"的长度为11个字符。请注意,strlen函数不包括null字符在内,所以字符串的实际长度是12个字符(包括null字符)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)