6用C语言实现.用一个函数来实现将一行字符串中最长的单词找出。此行字符串从主函数传递给该函数。
时间: 2024-06-13 17:09:09 浏览: 78
以下是用C语言实现将一行字符串中最长的单词找出的函数示例:
```c
#include <stdio.h>
#include <string.h>
void findLongestWord(char str[]) {
int i, j, len, maxLen = 0, start = -1;
char longest[100], temp[100];
len = strlen(str);
for (i = 0; i < len; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
if (start == -1) {
start = i;
}
} else {
if (start != -1) {
int tempLen = i - start;
strncpy(temp, &str[start], tempLen);
temp[tempLen] = '\0';
if (tempLen > maxLen) {
maxLen = tempLen;
strcpy(longest, temp);
}
start = -1;
}
}
}
if (start != -1) {
int tempLen = i - start;
strncpy(temp, &str[start], tempLen);
temp[tempLen] = '\0';
if (tempLen > maxLen) {
maxLen = tempLen;
strcpy(longest, temp);
}
}
printf("The longest word is: %s\n", longest);
}
int main() {
char str[100];
printf("Please enter a string: ");
fgets(str, 100, stdin);
findLongestWord(str);
return 0;
}
```
阅读全文