写一段c语言,求字符串长度程序。
时间: 2023-04-12 07:00:55 浏览: 136
可以使用strlen函数来求字符串长度,代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
printf("字符串长度为:%d\n", len);
return 0;
}
```
这段代码会让用户输入一个字符串,然后使用strlen函数求出字符串的长度,并输出结果。
相关问题
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字符)。
C语言求字符串中最长的单词 的长度
你可以使用以下代码来求字符串中最长的单词的长度:
```c
#include <stdio.h>
#include <string.h>
int longestWordLength(char *str) {
int maxLength = 0;
int currentLength = 0;
int i;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') {
if (currentLength > maxLength) {
maxLength = currentLength;
}
currentLength = 0;
} else {
currentLength++;
}
}
if (currentLength > maxLength) {
maxLength = currentLength;
}
return maxLength;
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
// 移除字符串末尾的换行符
str[strcspn(str, "\n")] = '\0';
int length = longestWordLength(str);
printf("最长的单词长度为:%d\n", length);
return 0;
}
```
这段代码会提示用户输入一个字符串,然后计算其中最长单词的长度,并输出结果。注意,此代码假设单词之间以空格分隔。如果你想要处理其他分隔符,可以进行相应的修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)