![](/img/trans.png)
[英]how to replace every match of a charecter in the entire string?? in 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>
您還需要進行兩項其他更改:
replace
返回void
,因此如果您希望replace
d字符串與原始字符串分開,則需要復制原始字符串並將其傳遞給replace
。 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.