如何从char指针值数组初始化字符串(char * ptr [])

时间:2014-10-19 11:04:31

标签: c++ arrays string argv

str是string,ptr是char指针数组。我需要使用ptr。

中包含的值初始化str
void help(char* ptr[]) {
    cout << ptr[0];
    cout << ptr[1];
    cout << ptr[2];
    cout << ptr[3];
    string str = ptr[0];
    cout << endl << str << endl;

}
int main(int argc, char* argv[]) {
    char arr1[] = "Hello";
    char arr2[] = "Hi" ;
    char arr3[] = "Blah";
    char arr4[] = "Blah";
    char* ptr[4];
    ptr[0] = arr1;
    ptr[1] = arr2;
    ptr[2] = arr3;
    ptr[3] = arr4;
    help(ptr);
}

2 个答案:

答案 0 :(得分:0)

如果我已正确理解您需要的是以下内容

#include <iostream>
#include <string>
#include <numeric>
#include <cstring>

std::string help( const char * ptr[], size_t n ) 
{
    size_t len = std::accumulate( ptr, ptr + n, ( size_t )0,
                                  []( size_t acc, const char *p )
                                  {
                                    return acc + std::strlen( p );
                                  } );

    std::string str;
    str.reserve( len );

    str = std::accumulate( ptr, ptr + n, str,
                           []( std::string &s, const char *p ) -> std::string &
                           {
                            return s += p;
                           } );

    return str;
}

int main() 
{
    const char * ptr[] =
    {
        "Hello ",
        "Hi ",
        "Blah ",
        "Blah "
    };          

    std::cout << help( ptr, sizeof( ptr ) / sizeof( *ptr ) ) << std::endl;

    return 0;
}

输出

Hello Hi Blah Blah 

答案 1 :(得分:-2)

这应该有用。

char ptr[] = "Hello";
string str(ptr);