What is the method for assigning values to a C++ string?
In C++, there are several ways to assign values to a string type.
- You can assign a string to another string directly using the assignment operator (=).
std::string str1 = "Hello";
std::string str2 = str1;
- Assigning string literals directly to string objects.
std::string str = "Hello World";
- The assign() function allows you to assign a string to another string.
std::string str1 = "Hello";
std::string str2;
str2.assign(str1);
- By using the assign() function and string slicing, you can assign a portion of a string to another string.
std::string str1 = "Hello World";
std::string str2;
str2.assign(str1, 0, 5); // 将str1的前5个字符赋值给str2
- By using the append() function, you can add one string to the end of another string.
std::string str1 = "Hello";
std::string str2 = " World";
str1.append(str2);
These methods can be chosen according to specific needs for appropriate assignment methods.