Detailed explanation of C++ string

C++ has greatly enhanced the support for strings. In addition to using C-style strings, you can also use the built-in string class. The string class is much more convenient to handle strings, and can completely replace character arrays or string pointers in C language.

string is a class commonly used in C++, it is very important, we need to explain it separately here.

To use the string class, you need to include the header file <string>. The following example introduces several ways to define string variables (objects):

    #include <iostream>
    #include <string>
    using namespace std;
    int main(){
        string s1;
        string s2 = "c plus plus";
        string s3 = s2;
        string s4 (5, 's');
        return 0;
    }

The variable s1 is just defined but not initialized, the compiler will assign the default value to s1, the default value is "", which is an empty string.

The variable s2 is initialized to when it is defined "c plus plus". Unlike C-style strings, there is no end-of-string marker '\0'.

When the variable s3 is defined, it is directly initialized with s2&#x

Guess you like

Origin blog.csdn.net/shiwei0813/article/details/132548310