我試圖做一個程序,使得輸入一個字符串,如「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」
感謝您的幫助。
我開始重新標記它作爲C++/CLI,但TBH它幾乎是純C++除了'args'(即未使用) – MSalters