簡體   English   中英

如何用另一個字符串替換字符串中的字符? 在c ++中

[英]How to replace a charecter in a string with another ?? in 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;                                                                                 
} 

你需要#include <algorithm> for std::replace ,但你還需要使用單個字符。 請注意單引號:

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

另請注意, replace將替換現有元素。 std::replace返回void

std::replace <algorithm>聲明 ,因此你必須#include <algorithm>

您還需要進行兩項其他更改:

  1. replace返回void ,因此如果您希望replace d字符串與原始字符串分開,則需要復制原始字符串並將其傳遞給replace
  2. replace取單個char ,而不是字符串; 但是你傳遞一個以"a""x"結尾的以字符結尾的字符串。

包含以下兩項更改的代碼:

std::string output_string = string_to_edit;
replace (output_string.begin(), output_string.end(), 'a', 'x');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM