2014-12-27 131 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; 
    } 
}