2014-12-27 133 views
0

我试图做一个程序,使得输入一个字符串,如“cccaaaattt”时的输出将是“猫”去除连续重复值

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

#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”

感谢您的帮助。

+0

我开始重新标记它作为C++/CLI,但TBH它几乎是纯C++除了'args'(即未使用) – MSalters

回答

3

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

#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

+0

我新会有一些简单的像这样。谢谢。你的用户名是相关的:) – TroyStacer

0

提示:当你有4个连续相同的字符,你有2对。您正确删除每一对的后半部分。

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; 
    } 
}