在stl中添加两个字符串
Adding two strings in stl
是否有任何方法可以添加两个字符串而不使用任何循环,如果有任何内置函数?
。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;
- 转换成两个
int
->atoi
- +他们
- 将结果转换为
string
->itoa
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 两个字符串之间的数学运算
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 给定两个字符串 S 和 T.确定与 T 相差最小的 S 子字符串?
- gtest:检查字符串是否等于两个字符串之一
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- 我可以在系统()中使用两个字符串吗?