C语言程序。输入一个句子,寻找其最长的单词。假设这句话中除了字母空格外,只存在两种标点符号——逗号(,)和句号(.)。 要求使用和编写如下函数: 求最长单词并输出,如max(char a[]);返回类型自定。
时间: 2024-12-06 11:23:49 浏览: 81
在C语言中,你可以创建一个函数`longest_word(char sentence[], char punctuations[])`来寻找给定字符串中最长的单词。这里的关键在于分割字符串,移除标点符号,并遍历字符串以找到最长的单词。以下是该函数的一个实现示例:
```c
#include <stdio.h>
#include <string.h>
// 定义一个常量数组存储允许的字符(字母)
#define ALPHABET_SIZE 26
char allowed_chars[] = "abcdefghijklmnopqrstuvwxyz,.";
// 函数用于查找最长单词
typedef struct {
int start;
int end;
} Word;
Word longest_word(char sentence[], char punctuations[]) {
// 初始化变量
int max_len = 0, current_len = 0;
Word result;
result.start = -1;
// 遍历整个句子
for (int i = 0; sentence[i] != '\0'; i++) {
if (strchr(punctuations, sentence[i]) == NULL && isalpha(sentence[i])) { // 检查当前字符是否为字母或标点符号外的字母
current_len++;
if (current_len > max_len) { // 更新最长单词信息
max_len = current_len;
result.end = i;
result.start = i - max_len + 1; // 记录单词起始位置
}
} else {
current_len = 0; // 如果遇到非字母字符,重置长度计数
}
}
// 返回结果
if (result.start != -1) { // 如果找到了单词
return result;
} else {
return (Word){-1, -1}; // 如果没有单词,返回空结果
}
}
int main() {
char sentence[] = "Hello, world! This is a test sentence.";
char punctuations[] = ",.";
Word longest = longest_word(sentence, punctuations);
if (longest.start != -1) {
printf("Longest word: %s\n", &sentence[longest.start]);
} else {
printf("No words found.\n");
}
return 0;
}
```
这个函数首先初始化最长单词的长度和起止位置,然后逐个字符遍历输入的句子。如果遇到字母,就增加当前单词长度;遇到标点符号或非字母字符则重置长度。当遍历完后,根据记录的信息找到最长单词并返回。
阅读全文