c++ - 删除字符串中连续的重复值

标签 c++

我正在尝试编写一个程序,以便在输入诸如“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/

相关文章:

c++ - c++ 中 std::vector 的 ArrayList 样式 indexOf?

c++ - 并行迭代器

c++ - std::atomic::load 的内存排序行为

c++ - 为什么使用 istreambuf 迭代器读取文件通过重复执行会变得更快?

c++ - 为什么数组没有形成?

c++ - 无法通过 odbc 连接到 Microsoft Azure 数据库

c++ - 在 C++ 中写入用户指定的文件

C++ 编译器驱动程序已停止工作

c++ - 为什么这种访问冲突会发生在/Og 和/GL 标志上,并带有传递引用?

c++ - 将 c_str() 存储为 char *