如何在c++中将字符串数组转换为字符串类型,例如将每个元素连接到一个字符串中,并在字符串上使用子字符串

How to convert a string array to string type in C++, as in concatenate every element together into one string, and use substring on the string?

本文关键字:字符串 一个 数组 c++ 转换 元素 类型 连接      更新时间:2023-10-16

例如:

读取文件输入并存储到

char fileInput[200];
然后我用 将它转换成某种字符串数组
string fileStrArr(fileInput);

文件的测试输出如下所示:50014002600325041805我怎么能使用一个循环子字符串来获得每个4位字符,并将其转换为一个数字,如"5001"4002"6003"…?我想我需要先把字符串数组变成字符串?

将字符数组转换为std::string类型的对象非常简单

std::string s( fileInput ); 

,前提是fileInput以零结束。否则你必须使用其他std::string构造函数

如果我没理解错的话,你需要以下内容

#include <iostream>
#include <string>
#include <vector>
int main()
{
    const size_t N = 4;
    std::string s( "50014002600325041805" );
    std::vector <int> v;
    for ( size_t i = 0; i != s.size(); )
    {
        std::string t = s.substr( i, N );
        v.push_back( std::stoi( t ) );
        i += t.size();
    }
    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;
    return 0;
}

程序输出为

5001 4002 6003 2504 1805 
相关文章: