這是一個程序: 首先,用戶輸入一個文本字符串(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