如何将char更改为字符串?

时间:2013-12-09 21:45:28

标签: c++ string map char

我有这个功能:

void map()
{
   map<char, string> change;  
   string usrstr = "A APPLE AND BANANA";

   change['A'] = "00011";
   change['B'] = "11001";
   change['C'] = "01110";
   change[' '] = "$$";

} 

我如何将字符串中所有出现的'A'更改为“00011”,将B,C和空格更改为相同。非常感谢所有帮助

P.S字符串不一定是相同的

2 个答案:

答案 0 :(得分:1)

不确定:怎么样:

std::string str = "A APPLE AND BANANA";
std::replace(str.begin(), str.end(), "A", "00011" );
std::replace(str.begin(), str.end(), "B", "11001" );
...

答案 1 :(得分:0)

您可以而且应该使用string::replace。 即使你最近的评论。

但这可能是你想要做的事情:

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>


using namespace std;


int main()
{
    char temp;

    map<char, char*> change;

    string lol = "A APPLE AND BANANA";

    change['A'] = "00011";
    change['B'] = "11001";
    change['C'] = "01110";
    change[' '] = "$$";


    for (int i = 0; i < lol.length(); i++)
    {
        temp = lol[i];
        if (change[temp])
            cout << change[temp];
        else
            cout << lol[i];
    }

    cout << endl;

    cin.get();
    return 0;
}