大家晚上好,
我正在尝试从字符串中删除重复的字母。我的循环无法正常工作。我的字符串是 "ABCBDE",我想打印 "ABCDE",但它打印 "ABCEDD"。顺序实际上并不重要,但我需要每封信只打印一次。有人发现我的代码中有错误吗?
谢谢
#include <stdio.h>
int main()
{
char str1[] = "ABCBDE";
printf("Available: %s\n", str1);
int len1 = strlen(str1);
int i = 0;
int j;
for(i; i < len1; i++){
for(j = i+1; j < len1+1; j++){
if (str1[i] == str1[j]) { // remove duplicated letter
str1 [j] = str1 [len1 - 1]; // replace with last
len1 --; // cut last
}
}
}
printf("Available: %s\n", str1);
return 0;
}
最佳答案
您的代码背后的逻辑实际上几乎是正确的。关键是要理解 j
只是当前字符的索引,将 j+N
复制到 j
将得到相同的字符串在类似 AAA
的情况下。您需要做的是反转您的 if
条件并添加一个变量来跟踪复制非重复字符的位置。下面是一些可以帮助您入门的代码:
for (int i = 0; i < len1; i++) {
// Index var used to track where to copy non-duplicate characters.
int di = i+1;
for (int j = di; j < len1+1; j++) {
if (str1[i] != str1[j]) {
/*
Replace this comment block with your code.
*/
}
}
}
提示:
- 如果
j
处的字符与i
处的字符不重复,我们可以复制j
处的字符来替换di
处的字符。 di
在每次复制完成后递增。- 2 行代码。
如果遇到问题,请尝试使用如下列表中的小字符串遍历代码的每一行。一步步。如有必要,请写在纸上。
Start => End A => A AA => A AAA => A AB => AB AAB => AB ABA => AB ABB => AB ABC => ABC
关于c - 如何从字符串中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114358/