如何用另一个字符串替换字符串中的字符?在c ++中

时间:2014-01-09 15:40:07

标签: c++

这是我的代码,但它说replace is not declared in this scope这不是正确的语法吗?

#include<iostream>                                                                          
#include<string>                                                                            


using namespace std;                                                                        

int  main ()                                                                                
{                                                                                           
  string string_to_edit;                                                                    
  cout<<"Enter a string to replace all the vowels:"<<endl;                                  
  cin>>string_to_edit;                                                                      
  string output_string=replace(string_to_edit.begin(),string_to_edit.end(),"a","x");               
  cout<<output_string<<endl;                                                                
  return 0;                                                                                 
} 

2 个答案:

答案 0 :(得分:5)

std::replace需要#include <algorithm>,但您还需要使用单个字符。请注意单引号:

replace(string_to_edit.begin(),string_to_edit.end(),'a','x');  

另请注意,replace将替换现有元素。 std::replace会返回void

答案 1 :(得分:3)

std::replacedeclared in <algorithm>,因此您必须#include <algorithm>

您还需要进行其他两项更改:

  1. replace返回void,因此如果您希望replace d字符串与原始字符串分开,则需要复制原始字符串并将其传递给{{ 1}}。
  2. replace需要单replace个,而不是字符串;但是你传递了一个以char"a"开头的以字母结尾的字符串。
  3. 包含这两项变更的代码:

    "x"