【问题标题】:How to convert a char array to a string?如何将char数组转换为字符串?
【发布时间】:2012-02-16 02:54:12
【问题描述】:

使用字符串的c_str 函数然后执行strcpy 将C++ string 转换为char 数组非常简单。但是,如何做到相反呢?

我有一个 char 数组,例如:char arr[ ] = "This is a test"; 要转换回: string str = "This is a test.

【问题讨论】:

    标签: c++ string char arrays


    【解决方案1】:
    #include <stdio.h>
    #include <iostream>
    #include <stdlib.h>
    #include <string>
    
    using namespace std;
    
    int main ()
    {
      char *tmp = (char *)malloc(128);
      int n=sprintf(tmp, "Hello from Chile.");
    
      string tmp_str = tmp;
    
    
      cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
      cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;
    
     free(tmp); 
     return 0;
    }
    

    输出:

    H : is a char array beginning with 17 chars long
    
    Hello from Chile. :is a string with 17 chars long
    

    【讨论】:

    • 免费(tmp)在哪里?字符串会解决这个问题吗?
    • 好问题。我认为 free 应该在那里,因为我使用的是 malloc。
    【解决方案2】:

    投票最多的答案中遗漏了一个小问题。也就是说,字符数组可能包含 0。如果我们将使用上面指出的带有单个参数的构造函数,我们将丢失一些数据。可能的解决方案是:

    cout << string("123\0 123") << endl;
    cout << string("123\0 123", 8) << endl;
    

    输出是:

    123
    123 123

    【讨论】:

    • 如果您使用std::string 作为二进制数据的容器并且不能确定该数组不包含“\0”,这是一个更好的答案。
    • 或者如果字符串数组不包含'\0'
    【解决方案3】:

    另一种解决方案可能如下所示,

    char arr[] = "mom";
    std::cout << "hi " << std::string(arr);
    

    避免使用额外的变量。

    【讨论】:

    • 您能否在答案中指出这与我的 Misticial 接受的答案有何不同?
    • @owlstead 请查看编辑。我只是简单地提出我的答案,因为当我第一次看到这个页面寻找答案时,我希望看到的正是我所希望看到的。如果像我一样愚蠢的人遇到此页面,但无法通过查看第一个答案来建立这种联系,我希望我的回答能帮助他们。
    • 这通常不适用于字符数组,仅当它们以 0 结尾时。如果您不能确保您的字符数组以 0 结尾,请为 std::string 构造函数提供一个长度,例如 this answer
    【解决方案4】:

    string 类有一个构造函数,它接受一个以 NULL 结尾的 C 字符串:

    char arr[ ] = "This is a test";
    
    string str(arr);
    
    
    //  You can also assign directly to a string.
    str = "This is another string";
    
    // or
    str = arr;
    

    【讨论】:

    • 它仍然可以工作。重载的赋值运算符采用const char*,因此您可以将字符串文字或字符数组传递给它(衰减到那个)。
    • @kingsmasher1:严格来说,"hello world" 形式的字符串数组。如果您使用sizeof("hello world"),它将为您提供数组的大小(即 12),而不是指针的大小(可能是 4 或 8)。
    • 请注意,这只适用于 constant 以 NULL 结尾的 C 字符串。 string 构造函数不适用于例如声明为 unsigned char * buffer 的传递参数字符串,这在字节流处理库中很常见。
    • 没有必要保持不变。如果您有任何 char 类型的字节缓冲区,则可以使用其他构造函数:std::string str(buffer, buffer+size);,但在这种情况下最好坚持使用std::vector&lt;unsigned char&gt;
    • 虽然可能很明显:str 在这里 不是 转换函数。它是字符串变量的名称。您可以使用任何其他变量名称(例如 string foo(arr);)。转换由隐式调用的 std::string 的构造函数完成。
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2019-08-04
    相关资源
    最近更新 更多