从字符串中的单词序列替换整个单词 [英] Replace whole words from a sequence of words in a string

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

问题描述

大家好,这是我的第一个问题,所以请注意我这是否有问题。

我想在不使用的情况下更换一些单词提升库或其他.hpp'。

我的第一次尝试是制作字符串的副本,效率很低。我并不为此感到骄傲,所以我将在我使用地址的第二次尝试中发布。

Hello, everybody, this is my first question, so please notice me if it''s something wrong with this.
I want to replace some words without using boost libraries or other .hpp''s.
My first attempt was to make a copy of the string, and it was quite inefficient. I''m not very proud of it, so I will post my second attempt where I use addresses.

void ReplaceString(std::string &subject, const std::string &search, const std::string &replace) 
{
    size_t position = 0;
    while ((position = subject.find(search, position)) != std::string::npos)	//if something f***s up --> failure
    {
         subject.replace(position, search.length(), replace);
         position = position + replace.length();
    }
}





因为效率不高我想用另一种东西,但是我被困;我想使用一个函数,如



Because It''s not very efficient I want to use another thing, but I got stuck; I want to use a function like

replace_stuff(std::string & a);

,使用string.replace()和string.find()一个参数(用for循环或其他东西解析它然后使用std :: map< std :: string,>这对我来说非常方便。



有谁可以帮我这个,拜托?几个月前我开始学习C ++,我不知道很多技巧和窍门。我的连贯性也有一些问题,请原谅我可怜的英语。

祝你好运,

乔治。



PS我想用它来输入大量的输入词。 (让我们说用无害的单词替换坏词)

with a single parameter using string.replace() and string.find() (parsing it with a for loop or something) and then make use of std::map <std::string,> which is very convenient for me.

Can anyone help me with this, please? I started learning C++ few months ago, and I don''t know many tips and tricks. I also have some problems with my coherence, so please excuse my poor English.
Best regards,
George.

P.S. I want to use it for a large number of input words. (let''s say replacing bad words with harmless ones)

推荐答案

你可以创建一个类,比如说 Replacer

You might create a class, say Replacer:
class Replacer 
{
  std::map<std::string,> replacement;

public:
  Replacer()
  {
     // init the map here
     replacement.insert ( std::pair<std::string,std::string>("C#","C++") );
     //...
  }
  void replace_stuff(std::string & a);
}





那么 replace_stuff 定义将非常类似于您的原始 ReplaceString (它将使用地图条目而不是传递的参数)。



Then the replace_stuff definition would be very similar to your original ReplaceString (it would use map entries instead of the passed parameters).


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

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