怎么用C语言写个程序找出两个英文句子中相同的英文单词

如题所述

一个扰敬示范程序大饥李州致如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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的特点之一啊?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-11-18
一个示范程序大致如下:唤和宴
#include <stdio.h>
#include <stdlib.h>棚基
#include <string.h>

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)
第2个回答  2012-11-16
如果不考虑效率问题的话陆誉,
可以定义两燃亩个字符串,赋值成两个英文句子皮悉森,
用两个嵌套for循环,一个单词一个单词的比较追问

能不能帮我举个程序例子?是不是要用到字符串数组,而且怎么把单词之间的空格符不算进去?

追答

声明两个字符串就可以,char a[ ]="i am a student"; char b[ ] = "i am a teacher";
用指针,指向每一个字母,当指针的值是空格的时候,即要指向下一个单词了
char *p=a;
while (*p != ' ')
{
p++;
} 这样可以跳过空格,可以根据你写的程序,决定是用while 或者是 if