C语言求字符串中最长的单词
时间: 2024-04-11 07:28:06 浏览: 203
可以使用C语言编写一个函数来求解字符串中最长的单词。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void findLongestWord(char str[]) {
char longestWord[100];
char currentWord[100];
int maxLength = 0;
int currentLength = 0;
int i, j;
for (i = 0, j = 0; i <= strlen(str); i++) {
if (str[i] != ' ' && str[i] != '\0') {
currentWord[j] = str[i];
j++;
currentLength++;
} else {
currentWord[j] = '\0';
if (currentLength > maxLength) {
maxLength = currentLength;
strcpy(longestWord, currentWord);
}
j = 0;
currentLength = 0;
}
}
printf("最长的单词是:%s\n", longestWord);
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
// fgets函数会在输入的字符串末尾添加一个换行符,需要将其替换为字符串结束符
if (str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = '\0';
}
findLongestWord(str);
return 0;
}
```
该代码中的 `findLongestWord` 函数用于找出字符串中最长的单词,并使用 `strcpy` 函数将其复制到 `longestWord` 字符数组中。最后,在 `main` 函数中获取用户输入的字符串,调用 `findLongestWord` 函数并输出结果。
请注意,该代码中假设单词之间以空格分隔。如果字符串中包含其他标点符号或特殊字符,需要根据具体需求进行相应的处理。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)