c++ - 替换 C++ 98 中的模式

标签 c++ string std c++98

我需要在字符串中为特定模式进行就地替换 示例:

输入:

temp.temp2..temp3....temp4......temp5

输出:

temp.temp2.temp3.temp4.temp5

所以基本上如果是单点,保持原样,但如果有更多连续的点,将它们替换为单点。

我尝试迭代字符串并根据比较复制到另一个字符串对象中,现在看起来真的很难看。 我想知道使用 C++ STL 有什么更好的方法吗?

最佳答案

如果你需要坚持使用 C++98,你可以使用 boost 正则表达式。

#include <boost/regex.hpp>
#include <iostream>

int main()
{
    std::string str = "....";
    boost::regex re("\\.{2,}");
    std::cout << regex_replace(str, re, ".") << std::cout;
}

如果你不能使用 boost,我想到的最简单的解决方案是:

#include <iostream>
#include <sstream>

using namespace std;

string replaceConsecutiveDots(const string& str) {
    std::stringstream ss;
    bool previousCharIsDot = false;
    for (string::const_iterator it = str.begin(); it!=str.end(); ++it) {
        char c = *it;
        if (c != '.' || !previousCharIsDot) {
            ss << c;
        }
        previousCharIsDot = c == '.';
    }
    return ss.str();
}

int main() {
    string str = "temp.temp2..temp3....temp4......temp5";
    cout << replaceConsecutiveDots(str) << endl;
}

关于c++ - 替换 C++ 98 中的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109906/

相关文章:

c++ - 在 C++ 中比较两个时间戳字符串

vb.net - 按最后一次出现拆分字符串

c++ - #include <fstream> visual c++ 2010 无法正常工作

c++ - CStatic 问题的背景颜色

c++ - 列出目标文件中 undefined reference

c# - 如何在字符串中只保留数字和一些特殊字符?

java - 智能解码十六进制输入(例如 0x32、0x3、32 等...)

c++ - 当我不在 C++ 中包含字符串头文件时出错

c++ - vector::shrink_to_fit 是否允许重新分配?

c# - Graphics.CopyFromScreen() 和 GetDC(0) 失败,返回 "The handle is invalid"