c语言输出两句话中最长的公共单词
时间: 2024-04-10 15:28:13 浏览: 15
你好!对于你的问题,我们可以编写一个函数来找到两句话中最长的公共单词。下面是一个例子:
```c
#include <stdio.h>
#include <string.h>
// 函数用于比较两个字符串并返回较长的字符串
const char* getLongerString(const char* str1, const char* str2) {
if (strlen(str1) >= strlen(str2)) {
return str1;
}
else {
return str2;
}
}
// 函数用于找到两句话中最长的公共单词
const char* findLongestCommonWord(const char* sentence1, const char* sentence2) {
char* token1 = strtok((char*)sentence1, " ");
char* token2 = strtok((char*)sentence2, " ");
const char* longestWord = "";
while (token1 != NULL) {
while (token2 != NULL) {
if (strcmp(token1, token2) == 0 && strlen(token1) > strlen(longestWord)) {
longestWord = token1;
}
token2 = strtok(NULL, " ");
}
token2 = strtok((char*)sentence2, " ");
token1 = strtok(NULL, " ");
}
return longestWord;
}
int main() {
const char* sentence1 = "I love coding in C";
const char* sentence2 = "C is a powerful programming language";
const char* longestWord = findLongestCommonWord(sentence1, sentence2);
printf("The longest common word is: %s\n", longestWord);
return 0;
}
```
在上面的例子中,我们定义了两个函数。`getLongerString` 函数用于比较两个字符串并返回较长的字符串。`findLongestCommonWord` 函数用于找到两句话中最长的公共单词。我们在 `main` 函数中使用了这两个函数来测试。
注意:这个例子假设两句话中的单词以空格分隔。如果有其他分隔符,请相应地修改代码。
希望这可以帮助到你!如果你有更多问题,请随时问我。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)