我花了最后一个半小时试图弄清楚如何string在C++中运行一个简单的搜索和替换对象.
我有三个字符串对象.
string original, search_val, replace_val;
Run Code Online (Sandbox Code Playgroud)
我想在运行一个搜索命令original的search_val,并与全部替换replace_val.
注意:仅限纯C++中的答案.环境是Mac OSX Leopard上的XCode.
Mar*_*ork 32
循环应该与查找和替换一起使用
void searchAndReplace(std::string& value, std::string const& search,std::string const& replace)
{
std::string::size_type next;
for(next = value.find(search); // Try and find the first match
next != std::string::npos; // next is npos if nothing was found
next = value.find(search,next) // search for the next match starting after
// the last match that was found.
)
{
// Inside the loop. So we found a match.
value.replace(next,search.length(),replace); // Do the replacement.
next += replace.length(); // Move to just after the replace
// This is the point were we start
// the next search from.
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4672 次 |
| 最近记录: |