MyMind

与这个世界交手多年,你是否光彩依旧,兴致盎然

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 C 语言的代码实现: ```c #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX_LEN 1000 void getCommonWord(char str1[], char str2[], char ans[]); int main() { char str1[MAX_LEN], str2[MAX_LEN], ans[MAX_LEN]; while (gets(str1) != NULL && gets(str2) != NULL) { getCommonWord(str1, str2, ans); if (strlen(ans) > 0) { printf("%s\n", ans); } else { printf("No common word!\n"); } } return 0; } void getCommonWord(char str1[], char str2[], char ans[]) { int i, j, k, len1, len2, max_len = 0; char word[MAX_LEN], max_word[MAX_LEN]; len1 = strlen(str1); len2 = strlen(str2); for (i = 0; i < len1; i++) { if (!isalpha(str1[i])) { word[0] = '\0'; } else { k = 0; while (isalpha(str1[i])) { word[k++] = str1[i++]; } word[k] = '\0'; i--; } for (j = 0; j < len2; j++) { if (!isalpha(str2[j])) { max_word[0] = '\0'; } else { k = 0; while (isalpha(str2[j])) { max_word[k++] = str2[j++]; } max_word[k] = '\0'; j--; } if (strcmp(word, max_word) == 0 && strlen(word) > max_len) { strcpy(ans, word); max_len = strlen(word); } } } } ``` 代码思路: 1. 定义 `getCommonWord` 函数,用于获取两个字符串中的最长公共单词。 2. 定义 `main` 函数,用于循环读入多组数据,每组数据通过调用 `getCommonWord` 函数获取最长公共单词并输出。 3. 在 `getCommonWord` 函数中,使用两层循环分别枚举两个字符串中的单词,通过比较两个单词是否相同,来获取最长公共单词。 注意事项: 1. 由于输入的字符串可能包含空格等非英文字母的字符,因此需要在获取单词时忽略这些字符。 2. 在比较两个单词是否相同时,需要使用 `strcmp` 函数来判断。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值