c语言比较两个单词大小,怎么用C语言写个程序找出两个英文句子中相同的英文单词...

一个示范程序大致如下:

#include

#include

#include

int main(int argc, char **argv)

{

char s1[] = "This is test sentence, find all duplicated words.";

char s2[] = "Just a test for finding duplication words.";

size_t len_s1 =0;

char *s_dup = NULL;

char* pch = NULL;

char* psubstr = NULL;

/* make a duplication to protect the source */

len_s1 = strlen(s1);

s_dup = (char*)malloc(len_s1 * sizeof(char));

if (s_dup == NULL)

{

fputs("Memory allocating error", stderr);

}

strncpy(s_dup, s1,len_s1);

/* slice the dup. string, loop thru 2nd string to compare word by word */

pch = strtok (s_dup, " ,."); /* modifying if necessary */

while (pch != NULL)

{

/* printf("%s\n", pch); */ /* debug print */

psubstr = strstr(s2, pch);

if (psubstr != NULL)

printf ("--->%s\n",pch);

pch = strtok (NULL, " ,.");

}

/* release memory allocated by malloc above */

free(s_dup);

return 0;

}

解析看不懂?求助智能家教解答查看解答

以下是一个简单的C语言程序,可以读取一个英文文本文件,查找所有给定的单词,并将它们替换为另一个单词,最后将修改后的文本保存到新文件: ```c #include <stdio.h> #include <string.h> #define MAX_LEN 1000 #define NUM_WORDS 3 int main() { char text[MAX_LEN], output[MAX_LEN]; char *keywords[NUM_WORDS] = {"apple", "banana", "orange"}; char *replace_word = "fruit"; int i, j, k, n, len, found; // 打开文本文件 FILE *fp = fopen("input.txt", "r"); if (fp == NULL) { printf("Failed to open file.\n"); return 1; } // 读取文本内容 fgets(text, MAX_LEN, fp); fclose(fp); // 替换所有匹配的单词 n = strlen(text); k = strlen(replace_word); j = 0; for (i = 0; i < n; i++) { found = 0; for (len = 0; len < NUM_WORDS; len++) { if (strncmp(&text[i], keywords[len], strlen(keywords[len])) == 0) { found = 1; break; } } if (found) { strncpy(&output[j], replace_word, k); j += k; i += strlen(keywords[len]) - 1; } else { output[j] = text[i]; j++; } } output[j] = '\0'; // 将修改后的文本保存到新文件 fp = fopen("output.txt", "w"); if (fp == NULL) { printf("Failed to create file.\n"); return 1; } fputs(output, fp); fclose(fp); return 0; } ``` 在上述代码,我们首先定义了一个常量 `MAX_LEN`,表示读取的文本内容的最大长度,以及一个常量 `NUM_WORDS`,表示要替换的单词数量。 然后,我们定义了一个字符串数组 `keywords`,存储要查找和替换的单词,以及一个字符串 `replace_word`,表示要替换成的新单词。 接下来,我们使用 `fopen()` 函数打开一个英文文本文件,并读取其的内容。 然后,我们使用两个循环遍历文本的所有字符,查找是否匹配任何一个要替换的单词。如果找到了匹配的单词,就将它替换为新单词;否则,将当前字符直接复制到输出字符串。 最后,我们使用 `fopen()` 函数创建一个新的文本文件,并将修改后的文本保存到该文件。 在运行该程序之前,需要将程序代码保存到一个C语言源代码文件,并将待处理的英文文本文件命名为 `input.txt`,放置在程序所在的同一个目录下。然后,我们只需要编译并运行C程序,即可生成修改后的文本文件 `output.txt`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值