题目:编写一函数,输入一行字符,将此字符串中最长的单词输出
#include <stdio.h>
#include <string.h>
void printLongestWord(char* str);
int main() {
char input[1024];
printf("请输入一行字符(回车结束):");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0;
printLongestWord(input);
return 0;
}
void printLongestWord(char* str) {
int maxLength = 0;
int currentLength = 0;
int startIndex = 0;
int isWord = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
if (!isWord) {
startIndex = i;
isWord = 1;
}
currentLength++;
}
else {
if (isWord) {
if (currentLength > maxLength) {
maxLength = currentLength;
startIndex = i - maxLength;
}
currentLength = 0;
isWord = 0;
}
}
}
if (isWord && currentLength > maxLength) {
maxLength = currentLength;
startIndex = strlen(str) - maxLength;
}
if (maxLength > 0) {
printf("最长的单词是:%.*s\n", maxLength, str + startIndex);
}
else {
printf("没有输入单词。\n");
}
}