这是一个程序: 首先,用户输入一个文本字符串(char text1;
); 然后,我通过复制数组中的每个单词来分隔字符串(char words[20][200]
);在C中逐字比较字符串
我想比较单词字符串并重复在text1
字符串中doensn't不重复的每个单词。在text1
中重复的单词将按原样复制到新字符串中(char text2
)。
实施例1: 如果用户输入 “hello world
” 然后结果必须是 “hello hello world world
”
实施例2: 如果用户输入 “weather is good weather
” 然后结果必须是 “weather is is good good weather
”
问题是,如果我输入“hello world
”那么结果我得到“hello hello world
“。
我该如何解决这个问题?
下面的代码:
#include <stdio.h>
#include <string.h>
int main()
{
char text1[200], text2[200], words[20][100], *dist;
int i, j, nwords=0;
// Text input
printf("\n Enter the text: ");
gets(text1);
// Separate text word by word
dist = strtok(text1, " ,.!?");
i=0;
while(dist!=0)
{
strcpy(words[i],dist);
dist = strtok(NULL, " ,.!?");
i++;
nwords++;
}
// Task
if(nwords=1)
{
strcat(text2,words[0]);
strcat(text2," ");
strcat(text2,words[0]);
}
for(i=0; i<nwords-1; i++)
for(j=i+1; j<nwords; j++)
{
if(strcmp(words[i],words[j])==0)
{
strcat(text2,words[i]);
}
else
{
strcat(text2,words[i]);
strcat(text2," ");
strcat(text2,words[i]);
}
}
// Result
printf("\n\nInput:\n");
puts(text1);
printf("\n\nResult:\n");
puts(text2);
getchar();
return 0;
}
'nvardi'?你的意思是nwords。 –
是的,抱歉我的错误。应该有“黑客”。 – Kurbads