如何在c++中添加cstring的元素
how to add the elements of cstrings in c++?
我想添加字符串的元素。例如想把a[5]和b[5]相加,答案应该是11,我该怎么做呢
#include<iostream>
#include<string>
using namespace std;
int main()
{
string a="12345";
string b="23456";
return 0;
}
考虑索引的有效范围为[0,4]。字符串a中没有元素a[5]
你可以用下面的方法做这个任务
std::cout << a.back() - '0' + b.back() - '0' << std::endl;
或
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string a = "12345";
std::string b = "23456";
std::transform( a.begin(), a.end(), b.begin(),
std::ostream_iterator<int>( std::cout, " " ),
[]( char c1, char c2 ) { return ( ( c1 -'0' ) + ( c2 - '0' ) ); } );
std::cout << std::endl;
return 0;
}
或
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string a = "12345";
std::string b = "23456";
std::string c;
c.reserve( a.size() );
int overflow = 0;
std::transform( a.rbegin(), a.rend(), b.rbegin(),
std::back_inserter( c ),
[&]( char c1, char c2 ) -> char
{
int s = ( c1 -'0' ) + ( c2 - '0' ) + overflow;
return ( overflow = s / 10, s % 10 + '0' );
} );
if ( overflow ) c.push_back( overflow );
std::reverse( c.begin(), c.end() );
std::cout << c << std::endl;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- MFC,如何获取CArray中的元素,哪个元素类型是CString
- 如何在c++中添加cstring的元素