我需要在字符串中为特定模式进行就地替换 示例:
输入:
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/