大佬教程收集整理的这篇文章主要介绍了c – 除非已经转义,否则如何替换字符串或字符的所有出现?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
以便
std::string s1("Hello 'world'"); my_replace(s1,"'","''"); // s1 becomes "Hello ''world''" std::string s2("Hello \\'world'"); // note: only a single BACkslash in the String my_replace(s2,"''"); // s2 becomes "Hello \\'world''"
使用boost :: regex,可以使用以下命令完成:
std::string my_replace (std::string s,std::string search,std::string format) { boost::regex e("([^\\\\])" + search); return boost::regex_replace(s,e,"\\1" + format); }
但由于性能原因,我不想使用boost :: regex. boost :: algorithm :: replace看起来很合适,但我无法确切知道如何.
#include <iostream> #include <String> using namespace std; String replace(char c,String replacement,String s) { String chars = String("\\") + c; size_t pos = s.find_first_of(chars); while (pos != String::npos) { char& ch = s[pos]; if (ch == '\\') { pos = s.find_first_of(chars,pos + 2); } else if (ch == C) { s.replace(pos,1,replacement); pos = s.find_first_of(chars,pos + replacement.length()); } } return s; } int main() { cout << replace('\'',"''","Hello \\'world'"); }
更新:
按照@ BenVoigt的建议,我重新制定了算法以避免就地操作.这应该会进一步提升绩效:
String replace(char c,String const& s) { String result; size_t searchStartPos = 0; String chars = String("\\") + c; size_t pos = s.find_first_of(chars); while (pos != String::npos) { result += s.substr(searchStartPos,pos - searchStartPos); if (s[pos] == '\\') { result += String("\\") + c; searchStartPos = pos + 2; } else if (s[pos] == C) { result += replacement; searchStartPos = pos + 1; } pos = s.find_first_of(chars,searchStartPos); } return result; }
以上是大佬教程为你收集整理的c – 除非已经转义,否则如何替换字符串或字符的所有出现?全部内容,希望文章能够帮你解决c – 除非已经转义,否则如何替换字符串或字符的所有出现?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。