怎么用C语言写个程序找出两个英文句子中相同的英文单词
发布网友
发布时间:2023-08-06 02:53
我来回答
共3个回答
热心网友
时间:2024-11-30 19:04
一个示范程序大致如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char s1[] = "This is test sentence, find all plicated words.";
char s2[] = "Just a test for finding plication words.";
size_t len_s1 =0;
char *s_p = NULL;
char* pch = NULL;
char* psubstr = NULL;
/* make a plication to protect the source */
len_s1 = strlen(s1);
s_p = (char*)malloc(len_s1 * sizeof(char));
if (s_p == NULL)
{
fputs("Memory allocating error", stderr);
}
strncpy(s_p, s1,len_s1);
/* slice the p. string, loop thru 2nd string to compare word by word */
pch = strtok (s_p, " ,."); /* 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_p);
return 0;
}追问如果不用指针该怎么做
追答① 哪一部分不希望是指针?
② 为什么不希望是指针? C的特点之一啊?
热心网友
时间:2024-11-30 19:05
一个示范程序大致如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char s1[] = "This is test sentence, find all plicated words.";
char s2[] = "Just a test for finding plication words.";
size_t len_s1 =0;
char *s_p = NULL;
char* pch = NULL;
char* psubstr = NULL;
/* make a plication to protect the source */
len_s1 = strlen(s1);
s_p = (char*)malloc(len_s1 * sizeof(char));
if (s_p == NULL)
热心网友
时间:2024-11-30 19:05
如果不考虑效率问题的话,
可以定义两个字符串,赋值成两个英文句子,
用两个嵌套for循环,一个单词一个单词的比较追问能不能帮我举个程序例子?是不是要用到字符串数组,而且怎么把单词之间的空格符不算进去?
追答声明两个字符串就可以,char a[ ]="i am a student"; char b[ ] = "i am a teacher";
用指针,指向每一个字母,当指针的值是空格的时候,即要指向下一个单词了
char *p=a;
while (*p != ' ')
{
p++;
} 这样可以跳过空格,可以根据你写的程序,决定是用while 或者是 if