如何有效地用不同的整数元素替换char字符串的元素?

Awa*_*One 2 c++ string integer replace

我期待用整数元素替换字符串的元素.我要替换A1,B2,C3D使用4.

我怎样才能有效地做到这一点?

#include <iostream>
#include <string>
#include <algorithm>


int main()
{
    std::string str = "ABCDDCBA";

    std::replace(str.begin(), str.end(), 'A', '1'); // Replacing 
    std::replace(str.begin(), str.end(), 'B', '2');  
    std::replace(str.begin(), str.end(), 'C', '3'); 
    std::replace(str.begin(), str.end(), 'D', '4');  
    // ...

    std::cout << str << std::endl; // displaying 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 5

使用另一个任意字符替换任意字符非常有效.

但是,目前您使用连续整数数字替换连续拉丁字母,因此您可以利用ASCII表示也是连续的这一事实:

for(char& c : str)
     c += '1' - 'A';
Run Code Online (Sandbox Code Playgroud)

当然,这取决于本机字符编码来表示具有连续值的连续拉丁字母,例如ASCII.它还取决于连续表示的数字,但这是标准规定的.

此外,此方法当前不检查替换的字符,并将更改所有遇到的字符.这不是输入字符串的问题,但如果您只想替换某些类型的字符并保持其他字符不变,那么您需要添加条件检查.