【发布时间】:2017-05-28 18:34:01
【问题描述】:
我正在寻找用整数元素替换字符串的元素。我想用1替换A,用2替换B,用3替换C,用4替换D。
我怎样才能有效地做到这一点?
#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;
}
【问题讨论】:
-
您的数据如此之小,您的程序如此简单,而今天的计算机如此之快,编译器如此之好,以至于几乎任何解决方案都将是有效的,甚至没有机会测量一个区别。
-
@ChristianHackl 有
2000000000长度 -
什么意思?长度为 18 的字符串?
-
还是指 2^9?那是512。它仍然什么都没有。你真的测量过速度吗?
标签: c++ string replace integer