标题: 在一个已知的字符串中查找最长单词,假定字符串中只含... [打印本页] 作者: 古月文阳 时间: 2015-11-27 20:00 标题: 在一个已知的字符串中查找最长单词,假定字符串中只含... #include <stdio.h>
#include <string.h>
int main() {
char str[] = "In a known to find the longest word in the string assume that the string contains only letters and Spaces the blank space to separate different words";
int maxCount = 0; // 记录最大长度
int index = 0; // 记录单词尾字符下标
for (int i = 0; i < strlen(str); ++i) {
int count = 0; // 记录新单词长度
while (str[i] != ' ' && str[i]) { // 字符不是空格也不是\0
++i;
++count;
}
if (count > maxCount) {
maxCount = count;
index = i - 1;
}
}
printf("最长单词是:");
for (int i = index - maxCount + 1; i <= index; ++i)
printf("%c", str[i]);
printf("\n");
return 0;
}