如何将像'A'这样的单个字符替换为类似"10"?
How do I replace a single character like 'A' with something like "10"?
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s;
cin >> s;
for (int i = 0; i < s.size (); i++)
{
if (s[i] == 'A')
{
s[i] = "10";
}
cout << s[i];
}
return 0;
}
我收到以下错误:
main.cpp: In function
'int main()': main.cpp:10:5: error: invalid conversion from 'const char*' to 'char' [-fpermissive] s[i]= "10";
任何帮助将不胜感激。谢谢。
你可以找到A
的位置,从索引 0 开始直到字符串的末尾,只要你找到,就用10
replace
它,使用你找到的位置和你想在给定字符串中找到的字符串长度的信息。
如下所示: https://www.ideone.com/dYvF8d
#include <iostream>
#include <string>
int main()
{
std::string str;
std::cin >> str;
std::string findA = "A";
std::string replaceWith = "10";
size_t pos = 0;
while ((pos = str.find(findA, pos)) != std::string::npos)
{
str.replace(pos, findA.length(), replaceWith);
pos += replaceWith.length();
}
std::cout << str << std::endl;
return 0;
}
为什么不使用string::find()
找到要替换的字符,然后string::insert
插入"10"? 也许不是最好的方法,但可以正确完成它。
你的代码的问题是std::string
的operator[]
返回一个char&
,并且你不能给它分配一个string literal
。
我想我应该给你一个函数来实现它。
void Process(std::string& op)
{
auto pos=op.find('A');
op.erase(pos,1);
if(pos!=std::string::npos)
{
op.insert(pos,"10");
}
}
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 删除/替换C++字符串中的多字符 (ÿû)
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 用 X 替换字符串中的字符C++练习
- 替换 2D 数组中的字符
- 替换字符阵列C 中的字符
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++字符数组查找/替换字符
- 如何使用C++快速就地替换字符
- 通过存储在向量中的字符串的字符迭代以替换字符C
- 如何在C++中读取带有ifstream的替换字符?(ASCII 中的 SUB)
- 替换字符,如替换全部(字符串,开始,结束,"_","-")
- 搜索和替换字符数组 c++ 中出现的所有字符串
- 在字符指针中用内存移动替换字符
- 函数,用于查找和替换字符数组(流)c++中的字符串
- 查找并替换字符数组中的单词
- 用字符串中的 int "替换"字符
- 替换字符数组中的单词
- 替换字符*中的字符
- C++:替换字符时出错