-
#include "stdafx.h" #include<string> #include<iostream> using std::string; using std::cout; using std::endl; //返回一个不含strOld string strReplaceAll(const string& strResource, const string& strOld, const string& strNew) { string::size_type pos = 0; string strTemp = strResource; do { if ((pos = strTemp.find(strOld)) != string::npos) { strTemp.replace(pos, strOld.length(), strNew); } } while (pos != string::npos); return strTemp; } //返回一个用strNew将strResource中的strOld从头到尾替换一遍后的字符串 string strReplaceAllOnce(const string& strResource, const string& strOld, const string& strNew) { string strTemp = strResource; string::size_type pos = 0; do { if ((pos = strTemp.find(strOld,pos)) != string::npos) { strTemp.replace(pos, strOld.length(), strNew); pos += strOld.length(); } else pos = string::npos; } while (pos != string::npos); return strTemp; } int _tmain(int argc, _TCHAR* argv[]) { string strResource = "hello"; string strNew = "le"; string strOld = "el"; //按位置替换 strResource.replace(strResource.begin(), strResource.begin() + 2, strNew); //按指定字符串替换 cout << strReplaceAll(strResource, strOld, strNew) << endl; cout << strReplaceAllOnce(strResource, strOld, strNew) << endl; return 0; }
字符串替换之C++
最新推荐文章于 2025-03-18 17:55:00 发布