首页 文章

如何将char数组转换为字符串?

提问于
浏览
211

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

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

4 回答

  • 322

    在最高投票的答案中错过了一个小问题 . 也就是说,字符数组可能包含0.如果我们将使用带有单个参数的构造函数,如上所述,我们将丢失一些数据 . 可能的解决方案是:

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

    输出是:

    123 123 123

  • 20

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

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

    这避免了使用额外的变量 .

  • 9
    #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;
    }
    

    OUT:

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

    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;
    

相关问题