C++ string initialization
To initialize a string in C++, you can use one of the following methods:
Initialization with a string literal:
cpp std::string str = "Hello, World!";
Explanation: In this method, the string literal "Hello, World!" is assigned to the variablestr
. The string literal is enclosed in double quotes and is automatically converted into astd::string
object.Initialization with another string:
cpp std::string str1 = "Hello"; std::string str2 = str1;
Explanation: In this method, the stringstr1
is initialized with the string literal "Hello". Then, the stringstr2
is initialized with the value ofstr1
. The value ofstr1
is copied tostr2
, creating a separate copy of the string.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 stringstr1
is initialized with the string literal "Hello, World!". Then, thesubstr()
function is used to extract a substring fromstr1
starting at index 0 and containing 5 characters. The resulting substring is assigned tostr2
.Initialization with a character array:
cpp char arr[] = "Hello, World!"; std::string str(arr);
Explanation: In this method, a character arrayarr
is initialized with the string literal "Hello, World!". Then, the character array is passed as an argument to thestd::string
constructor, which creates astd::string
objectstr
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.