我试图做一个程序,使得输入一个字符串,如“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