如何在c++中添加cstring的元素

how to add the elements of cstrings in c++?

本文关键字:cstring 元素 添加 c++      更新时间:2023-10-16

我想添加字符串的元素。例如想把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;
}