c语言写一个函数,输人一行字符,将此字符串中最长的单词输出。
时间: 2023-12-18 11:51:04 浏览: 94
输出最长单词.c
好的,我可以回答这个问题。以下是一个用C语言写的函数,它可以输入一行字符串,并输出其中最长的单词:
```
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void findLongestWord(char sentence[]) {
int len = strlen(sentence);
int longestLength = 0, currentLength = 0;
char longestWord[100], currentWord[100];
int wordStartIndex = 0, wordEndIndex = 0;
for (int i = 0; i <= len; i++) {
if (sentence[i] == ' ' || sentence[i] == '\0') {
currentLength = wordEndIndex - wordStartIndex;
strncpy(currentWord, &sentence[wordStartIndex], currentLength);
currentWord[currentLength] = '\0';
if (currentLength > longestLength) {
longestLength = currentLength;
strncpy(longestWord, currentWord, longestLength);
longestWord[longestLength] = '\0';
}
wordStartIndex = i + 1;
} else {
wordEndIndex = i;
}
}
printf("最长的单词是:%s\n", longestWord);
}
```
使用以上代码,你可以输入一行字符串,并找到其中最长的单词。希望对你有所帮助!
阅读全文