Converting a C-style string to a C++ std::string

后端 未结 6 1509
梦如初夏
梦如初夏 2020-12-14 00:42

What is the best way to convert a C-style string to a C++ std::string? In the past I\'ve done it using stringstreams. Is there a better way?

相关标签:
6条回答
  • 2020-12-14 01:07

    You can initialise a std::string directly from a c-string:

    std::string s = "i am a c string";
    std::string t = std::string("i am one too");
    
    0 讨论(0)
  • 2020-12-14 01:09

    If you mean char* to std::string, you can use the constructor.

    char* a;
    std::string s(a);
    

    Or if the string s already exist, simply write this:

    s=std::string(a);
    
    0 讨论(0)
  • 2020-12-14 01:14

    Check the different constructors of the string class: documentation You maybe interested in:

    //string(char* s)
    std::string str(cstring);
    

    And:

    //string(char* s, size_t n)
    std::string str(cstring, len_str);
    
    0 讨论(0)
  • 2020-12-14 01:21

    C++11: Overload a string literal operator

    std::string operator ""_s(const char * str, std::size_t len) {
        return std::string(str, len);
    }
    
    auto s1 = "abc\0\0def";     // C style string
    auto s2 = "abc\0\0def"_s;   // C++ style std::string
    

    C++14: Use the operator from std::string_literals namespace

    using namespace std::string_literals;
    
    auto s3 = "abc\0\0def"s;    // is a std::string
    
    0 讨论(0)
  • 2020-12-14 01:21

    In general (without declaring new storage) you can just use the 1-arg constructor to change the c-string into a string rvalue :

    string xyz = std::string("this is a test") + 
                 std::string(" for the next 60 seconds ") + 
                 std::string("of the emergency broadcast system.");
    

    However, this does not work when constructing the string to pass it by reference to a function (a problem I just ran into), e.g.

    void ProcessString(std::string& username);
    ProcessString(std::string("this is a test"));   // fails
    

    You need to make the reference a const reference:

    void ProcessString(const std::string& username);
    ProcessString(std::string("this is a test"));   // works.
    
    0 讨论(0)
  • 2020-12-14 01:23

    C++ strings have a constructor that lets you construct a std::string directly from a C-style string:

    const char* myStr = "This is a C string!";
    std::string myCppString = myStr;
    

    Or, alternatively:

    std::string myCppString = "This is a C string!";
    

    As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)

    0 讨论(0)
提交回复
热议问题