C++ string initialization

To initialize a string in C++, you can use one of the following methods:

  1. Initialization with a string literal: cpp std::string str = "Hello, World!"; Explanation: In this method, the string literal "Hello, World!" is assigned to the variable str. The string literal is enclosed in double quotes and is automatically converted into a std::string object.

  2. Initialization with another string: cpp std::string str1 = "Hello"; std::string str2 = str1; Explanation: In this method, the string str1 is initialized with the string literal "Hello". Then, the string str2 is initialized with the value of str1. The value of str1 is copied to str2, creating a separate copy of the string.

  3. Initialization with a substring of another string: cpp std::string str1 = "Hello, World!"; std::string str2 = str1.substr(0, 5); Explanation: In this method, the string str1 is initialized with the string literal "Hello, World!". Then, the substr() function is used to extract a substring from str1 starting at index 0 and containing 5 characters. The resulting substring is assigned to str2.

  4. Initialization with a character array: cpp char arr[] = "Hello, World!"; std::string str(arr); Explanation: In this method, a character array arr is initialized with the string literal "Hello, World!". Then, the character array is passed as an argument to the std::string constructor, which creates a std::string object str with the same value as the character array.

These are some of the common ways to initialize a string in C++. Each method has its own use cases and advantages, so choose the one that best suits your needs.