C++ 如何用一个字符(C+;+;)替换多个字符?
我们有一个字符。我们需要将字符中的所有C++ 如何用一个字符(C+;+;)替换多个字符?,c++,C++,我们有一个字符。我们需要将字符中的所有ab字符替换为字母c #include <iostream> #include <string> int main() { std::string s = "abracadabra"; int pos = -1; while ((pos = s.find("ab")) != -1)//finding the position of ab s.replac
ab
字符替换为字母c
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra
例如:
abracadabra
输出将是:
cracadcra
<>我尝试从C++使用<代码>替换()/<代码>函数,但没有成功。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here
#包括
#包括
使用名称空间std;
int main()
{
串试验;
cin>>试验;
对于(int i=0;i您可以使用C++11正则表达式:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
#包括
#包括
#包括
int main(){
std::string str=“abracadabra”;
标准::正则表达式r(“ab”);
标准::cout问题:
这不是std::string::replace
的语法
解决方案:
如前所述,语法是std::string::replace(size\t pos,size\t len,const string&str)
.Dotest.replace(i,2,“c”)
而不是test.replace(test[i],'c')
或者使用dtell指出的正则表达式
附加信息:
使用名称空间std;
被认为是一种不好的做法(更多信息)
使用std::string
时,应使用std::string::size
而不是strlen
要使用std::string
,您应该使用#include
而不是#include
完整代码:
#包括
int main()
{
字符串测试;
标准:cin>>试验;
for(无符号整数i=0;i std::cout使用标准库可以做的最简单的事情是首先查找ab
,然后替换它。我编写的示例代码是查找字符串ab
,除非字符串中没有,否则将其替换为c
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra
#包括
#包括
int main()
{
std::string s=“abracadabra”;
int pos=-1;
while((pos=s.find(“ab”))!=-1)//查找ab的位置
s、 替换(位置,尺寸(“ab”)-1,“c”);//将ab替换为c
std::您尝试过什么?您在哪里遇到了问题?请说明为什么不使用test.size()
而不是strlen()
?谢谢,我不知道regex函数。非常感谢。关于你的观点#3:标准不能保证
已经包含在
中,因此正确和可移植的方法是在使用std::string
时显式地包含。感谢你的反馈!好吧,regex解决方案是一个好方法可以说更简单。但他不懂正则表达式,你可以从他的代码中看出:)谢谢。好建议。