编写一个函数,能够将输入的字符串中最长的单词输出,如果有多个一样长就都输出的函数C语言
时间: 2024-12-18 09:37:42 浏览: 11
在 C 语言中编写一个函数来找出字符串中最长的单词并返回所有的最长单词可以分为两步:首先,我们需要分割字符串成单词数组;然后遍历这个数组找到最长的单词。这里是一个简单的示例:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 定义一个结构体存储单个单词及其长度
typedef struct {
char* word;
int length;
} Word;
// 函数用于分割字符串并返回单词数组
Word** split_string(char* str) {
char* temp = strtok(str, " ");
Word** words = (Word**)malloc(sizeof(Word*) * (strlen(str) ? 0 : 1));
if (!words)
return NULL;
int index = 0;
while (temp != NULL) {
words[index] = (Word*)malloc(sizeof(Word));
words[index]->word = strdup(temp);
words[index]->length = strlen(words[index]->word);
temp = strtok(NULL, " ");
index++;
}
return words;
}
// 函数用于查找最长的单词并返回结果
void find_longest_words(Word** words, int size, char*** longest_words) {
*longest_words = (char***)malloc(sizeof(char**) * size);
int maxLength = 0;
for (int i = 0; i < size; i++) {
if (words[i]->length > maxLength) {
maxLength = words[i]->length;
// 清空之前的结果
if (*longest_words)
free(*longest_words);
*longest_words = (char***)malloc(sizeof(char*) * (maxLength + 1));
if (*longest_words == NULL)
return;
}
// 将当前单词添加到最长单词列表
(*longest_words)[maxLength] = (char*)strdup(words[i]->word);
(*longest_words)[maxLength][words[i]->length] = '\0';
}
}
// 主函数示例
int main() {
char* input_str = "Hello world, this is a test string with multiple long words";
Word** words = split_string(input_str);
int word_count = 0;
if (words) {
word_count = strlen(input_str) / sizeof(char) - 1;
char*** longest_words = (char***)malloc(sizeof(char**) * word_count);
find_longest_words(words, word_count, longest_words);
printf("Longest words:\n");
for (int i = 0; i <= maxLength; i++) {
printf("%s\n", longest_words[i]);
}
// 释放内存
for (int i = 0; i <= maxLength; i++)
free(longest_words[i]);
free(words);
free(longest_words);
}
return 0;
}
阅读全文