String.replace功能

时间:2014-04-23 04:32:46

标签: c++ string

我不确定我是否完全理解string.replace功能

是否可以用“< array index>”替换单词

例如,给定words[] = { "have", "has", "are", "is", ... }

“这是一句话。”最终看起来像

“这< 3>一句话。”

或者我应该使用其他功能吗?

2 个答案:

答案 0 :(得分:2)

此处没有内置功能。编程通常不是选择一个完全符合你想要的函数,而是完成组合函数。

所以你需要的是

  • 对输入中的所有字词进行循环
  • 搜索列表中的单词
  • 生成替换的一些代码
  • 与string.replace

答案 1 :(得分:0)

std::string::replace()用于将一个字符串替换为另一个字符串 - 替换可以是基于位置的,但是您只能用其他字符串替换字符串。您不能使用string::replace()在字符串中间嵌入int值。见std::string::replace

// replacing in a string
#include <iostream>
#include <string>

int main ()
{
  std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '\n';
  return 0;
}

@Brian和@MSalters为您提供了一些关于如何解决问题的好建议,可以通过多种方式解决。

相关问题