字符串在C ++中替换 [英] String Replace in C++

查看:751
本文介绍了字符串在C ++中替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了最后一个半小时试图找出如何在C ++中的字符串对象上运行一个简单的搜索和替换。

I've spent the last hour and a half trying to figure out how to run a simple search and replace on a string object in C++.

我有三个字符串对象。

string original, search_val, replace_val;

我要在原始 search_val 并用 replace_val 替换所有出现。

I want to run a search command on original for the search_val and replace all occurrences with replace_val.

注意:仅适用于纯C ++的答案。环境是Mac OSX Leopard上的XCode。

NB: Answers in pure C++ only. The environment is XCode on the Mac OSX Leopard.

推荐答案

循环应该与find和replace

A loop should work with find and replace

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. 
    }
}

这篇关于字符串在C ++中替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆