How do you create a string in C++?

In C++, you can use the std::string class to create strings. Here are some common methods for creating strings:

  1. Create strings using string literals.
std::string str = "Hello, World!";
  1. A standard string
std::string str("Hello, World!");
  1. I only need one choice.
std::string str1 = "Hello";
std::string str2 = "World";
std::string str = str1 + ", " + str2 + "!";
  1. add()
std::string str = "Hello";
str.append(", World!");
  1. add()
std::string str = "Hello";
str.insert(5, ", World!");
  1. Extract a portion of a string
std::string str = "Hello, World!";
std::string subStr = str.substr(7, 5); // 从索引7开始截取长度为5的子字符串

These are just some common methods for creating strings, in fact, there are many other operations and functions that can be used to create and manipulate strings.

bannerAds