删除字符串中的连续重复值

时间:2014-12-27 02:10:23

标签: c++

我正在尝试创建一个程序,以便在输入诸如“cccaaaattt”之类的字符串时输出将是“cat”

到目前为止,这是我的代码:

#include "stdafx.h"
#include <iostream>
#include <string>


using namespace std;

int main(array<System::String ^> ^args)
{
    string str = "";//create an empty string variable named str
    std::cout << "What word do you want to remove duplicate characters from?";
    cin >> str; //fill the str variable with the word the user whants to remove duplicate consecutive characters from
    char current;//create a new char variable named current
    char lastChar;//create a new char variable named lastChar for the previos character in the string

for (int i = 1; i < str.length(); i++){ //iterate through until it reaches the end of the string
    lastChar = str[i - 1]; //set lastChar to the previos char in the string
    current = str[i];//set current to the current char in the string
    if (lastChar == current){//if the lastChar and the current are equal (the string has two consecutive characters
        str.erase(i,1);//erase the current character
    }

}
cout << str << endl; //display the new string
system("pause");
return 0;

}

我评论了我认为代码会做的事情。

它不会删除正确数量的字符,使我的输出“ccaatt”

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

在C ++中执行此操作的一种非常简单有效的方法是使用算法库中的std::uniqueerasestd::string函数。

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string x("xxbbbbccccczzzzxxxx");
    x.erase(std::unique(x.begin(), x.end()), x.end());
    std::cout << x << "\n";
}

这将输出:

  

xbczx

答案 1 :(得分:2)

虽然使用std::unique执行此作业,但您的错误是您在erase之后增加了计数器。固定的实现:

for (int i = 1; i < str.length(); /* No increment here */ ) {
    if (str[i - 1] == str[i]) {
        str.erase(i, 1);
    } else {
        ++i;
    }
}
相关问题