【问题标题】:How do I replace a single character like 'A' with something like "10"?如何用“10”之类的字符替换“A”之类的单个字符?
【发布时间】:2018-10-09 13:21:48
【问题描述】:
#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";

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 为什么我不能编辑这个问题来改变代码格式?

标签: c++ arrays c++11 replace stdstring


【解决方案1】:

为什么不使用string::find() 定位要替换的字符,然后使用string::insert 插入“10”?也许不是最好的方法,但可以正确完成。

你代码的问题是std::string的operator[]返回一个char&amp;,你不能给它分配一个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");
    }
}

【讨论】:

  • 为简单起见,这里就不介绍这个函数了,特别是因为它不在原来的问题中
  • 我投票赞成用find 替换循环。我想补充一点,假设std::size_t 这里是一个实现细节。使用auto pos = op.find(); 适应库会更好。或者,如果 C++11 不是一个选项:std::string::size_type pos = ...;
  • 您根本没有用11 替换 A,您只是在@987654335 旁边插入 11 @.
  • @RemyLebeau 哈哈,我忘记删了,抱歉,编辑答案!
  • @TomdeGeus 有道理,但我编写函数只是因为易于编写和可重用。
【解决方案2】:

你可以找到A的位置,从索引0开始直到字符串的结尾,每当你找到时,replace它和10使用你找到的位置和字符串长度的信息您想在给定的字符串中查找。

类似如下: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;
}

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2012-02-23
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多