删除重复的字符并放在c ++的字符串末尾

时间:2013-09-20 12:46:00

标签: c++ string

我正在尝试用c ++标题,但没有弄清楚  这是我试过的

char *str=new char[100];
cout<<"enter the string";
cin.getline(str,100);
int len=strlen(str);
int i=0;
//iterating through the string
while(i<len-1)
{
    int signal=0;
    char x;
    int j=i+1;
    while(j<len)
    {
        if(str[j]==str[i])
        {
            x=str[i];
            for(int k=j;k<len;k++)
            {
                str[k]=str[k+1];
            }
            len--;
            signal=1;
        }
        else
        {
            j++;
        }
    }
    if(signal==1)
    {
        for(int l=i;l<len;l++)
        {
            str[l]=str[l+1];
        }
        str[len-1]=x;
    }
}
cout<<str;

在这段代码中我还没有完成i ++,请告诉我在哪里做i ++ 或者你可以告诉一个简单而简单的代码来实现这一点。

这是你的时间。

1 个答案:

答案 0 :(得分:1)

使用std :: string更容易:

     std::string input("Darren");
     std::string uniqueCharsString, repeatedCharsString;

     for (int i = 0; i < input.length(); ++i)
     {
        // If we are looking at the last character, we need to compare it with the previous one
        if (i == input.length() - 1)
        {
           // If the character is the same as the previous one, add it to the repeatedCharsString
           if (input.at(i) == input.at(i-1))
              repeatedCharsString.push_back(input.at(i));
           // If the character is not the same as the previous one, add it to the uniqueCharsString
           else
              uniqueCharsString.push_back(input.at(i));
        }
        // If the character is the same as the following one, add it to the repeatedCharsString
        else if (input.at(i) == input.at(i+1))
        {
           repeatedCharsString.push_back(input.at(i));
           // Skip the next character since we already know it's the same as the previous one
           i++;
        }
        // If the character is not the same as the following one, add it to the uniqueCharsString
        else
           uniqueCharsString.push_back(input.at(i));
     }
     std::string result(uniqueCharsString + repeatedCharsString);

字符串比较区分大小写。

希望这有帮助!