嗨,我只是在寻求帮助,我写了一段快速代码来接受一个字符数组,然后通过一个函数运行,该函数将删除所有重复的字符我有一个小错误,因为它没有删除最后一个这里重复的字母是代码,我也将在代码之后放入输出中..
#include <iostream>
#include <fstream>
#include <ostream>
using namespace std;
const int max_num_chars=10;
void deleteRepeats(char c[], int& size);
int main()
{
char c[]={'a','b','b','b'};
int c_size=4;
cout<<"This Program reads characters into a partially filled array and then delete's repeats! \n";
cout<<"Here is the original array \n";
for (int i=0;i<c_size;i++)
{
cout<<c[i]<<"\n";
}
deleteRepeats(c, c_size);
cout<<"Here is the array after the deleteRepeats function! \n";
for (int i=0;i<c_size;i++)
{
cout<<c[i]<<"\n";
}
system("pause");
return 0;
}
void deleteRepeats(char c[],int& size)
{
int num = size;
int start = 0;
while(start != num)
{
char test = c[start];
for(int i = start+1; i <= num;i++)
{
if(test==c[i])
{
for(int j = i;j<num;j++)
{
c[j] = c[j+1];
}
num-=1;
}
}
start +=1;
}
size = num;
}
这是输出... 该程序将字符读入一个部分填充的数组,然后删除的重新 泥炭! 这是原始数组 A b b b 这是 deleteRepeats 函数之后的数组! A b b 按任意键继续 。 . .
抱歉,我只是通过添加这段代码来解决这个问题
for(int j = i;j<num;j++)
{
c[j] = c[j+1];
}
num-=1;
start-=1;
最佳答案
虽然对此有更好的算法。 在你的情况下:
在函数“deleteRepeats”中,在循环“for(int i = start+1; i <= num;i++)”中
当您删除下一个相同的元素时,您正在增加“i”,而没有考虑现在在相同的“i”处,删除后也可能有重复的元素。
解决方案: 删除元素后,也减少 i 的值。 所以现在你的循环看起来像这样
for(int i = start+1; i <= num;i++)
{
if(test==c[i])
{
for(int j = i;j<num;j++)
{
c[j] = c[j+1];
}
num-=1;
// correction
i--;
// correction
}
}
如有理解上的问题,请回复...
关于C++ Char Array删除重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204082/