我有这样一个算法来删除字符串中的重复单词:
int main()
{
char str[100], word[100], doubleArr[10][30];
int i = 0, j = 0, k = 0, len1 = 0, len2 = 0, l = 0, n, c = 0;
printf("Enter the stringn");
gets(str);
n = strlen(str);
for (i = 0; str[i] != ' '; i++) {
if (str[i] == ' ') {
doubleArr[k][j] = ' ';
k++;
j = 0;
} else {
doubleArr[k][j] = str[i];
j++;
}
}
doubleArr[k][j] = ' ';
j = 0;
for (i = 0; i < k; i++) {
for (l = 1; l < k + 1; l++) {
if (doubleArr[l][j] == ' ' || l == i) {
continue;
}
if (strcmp(doubleArr[i], doubleArr[l]) == 0) {
doubleArr[l][j] = ' ';
}
}
}
j = 0;
for (i = 0; i < k + 1; i++) {
if (doubleArr[i][j] == ' ') {
continue;
} else {
printf("%s ", doubleArr[i]);
}
}
}
我需要对字符串中的重复单词做一个计数器
当我尝试将计数器放在代码的不同位置时,我总是得到错误的结果。
要计算重复,只需在检测到一个时增加计数器,在测试if (strcmp(doubleArr[i], doubleArr[l]) == 0)
之后请注意,在你的代码中有许多小问题:
- 你不应该使用
gets()
- 你应该只在当前单词至少有1个字符时增加单词计数
k
。 - 如果句子不以空格结束,则单词计数可能不正确:如果
j > 0
在循环结束后增加它,并在其余代码中使用k
而不是k + 1
。 - 如果任何一个单词超过29个字符,或者由于缓冲区溢出而超过10个单词,则代码具有未定义行为。
下面是修改后的版本:
#include <stdio.h>
#include <string.h>
int main(void) {
char str[100], words[50][100];
int i, j, k, n, dup;
// input the string with fgets
printf("Enter the stringn");
if (!fgets(str, sizeof str, stdin))
return 1;
// extract the words from the string
j = n = 0;
for (i = 0; str[i] != ' '; i++) {
// use space and newline as word separators
if (str[i] == ' ' || str[i] == 'n') {
if (j > 0) {
// add a new word if not empty
words[n][j] = ' ';
n++;
j = 0;
}
} else {
words[n][j] = str[i];
j++;
}
}
// add the last word if not empty
if (j > 0) {
words[n][j] = ' ';
n++;
}
// remove duplicates
dup = 0;
k = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < k; j++) {
if (strcmp(words[i], words[j]) == 0)
break;
}
if (j == k) {
// keep this word
if (i != k) {
strcpy(words[k], words[i]);
}
k++;
} else {
// omit this word
dup++;
}
}
// update word count
n = k;
// output the word list
for (i = 0; i < n; i++) {
printf("%s%c", words[i], " n"[i == n - 1]);
}
printf("%d duplicatesn", dup);
return 0;
}
创建一个全局变量,例如int counter = 0;
。
那么第32行中的if
语句应该看起来像:
if (strcmp (doubleArr[i], doubleArr[l]) == 0) {
doubleArr[l][j] = ' ';
counter += 1;
}
然后你可以打印到任何你想要的地方:
printf("%d", counter);