我正在尝试编写一个程序,以便在输入诸如“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”
感谢您的帮助。
最佳答案
在 C++ 中,一种极其简单有效的方法是使用 std::unique
来自算法库和 erase
std::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
关于c++ - 删除字符串中连续的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663775/