在stl中添加两个字符串

Adding two strings in stl

本文关键字:两个 字符串 stl 添加      更新时间:2023-10-16

是否有任何方法可以添加两个字符串而不使用任何循环,如果有任何内置函数?

。E如果第一个字符串是"1234",第二个字符串是"0010"(这两个字符串的长度总是相同的),我可以把它们加起来得到"1244"而不使用循环吗?

疑问句中疑问句:如果长度不相同怎么办?

PS:长度不相同我的意思是:即,如果字符串A;其中A的长度为4,值为'1','12','12','10'和字符串b;其中b是"1234",然后加上"2","14","15","14"。结果也是长度为4,但请注意,它是根据索引添加的。

是的,看一下下面的代码:

std::string A("123"), B("321");
int res = std::stoi(A) + std::stoi(B);

c++ 11及以上版本:

std::string result = std::to_string(std::stoi(s1) + std::stoi(s2));

从历史上看,您必须使用像strtol或字符串流这样的c库函数,记住检查结果,如果字符串有可能不包含数字。

试试这个:

 std::string s1 = "1234";
 std::string s2 = "0010";
 int s = atoi(s1.c_str()) + atoi(s2.c_str());
 std::stringstream ss;
 ss << s;
 cout << ss.str() << endl;
  1. 转换成两个int -> atoi
  2. +他们
  3. 将结果转换为string -> itoa