C++ strings


In C++, strings are a sequence of characters that are represented as an object of the std::string class. 

The std::string class is defined in the <string> header file.


Here are some basic operations you can perform on C++ strings:


Initialization: You can initialize a string with a constant character array, a C-style string, or another string object.


cpp code


std::string str1 = "Hello";

 // initialization with a constant character array std::string str2 = " World"; 

// initialization with a C-style string std::string str3 = str1 + str2; 

// initialization by concatenating two string objects 


Accessing characters: You can access individual characters of a string using the array subscript operator [] or the at() method.


cpp code


char ch = str1[0]; 

// access first character using the array subscript operator ch = str1.at(1); //

 access second character using the at() method 


Concatenation: You can concatenate two strings using the + operator or the append() method.


cpp code


std::string str4 = str1 + str2;

 // concatenation using the + operator str1.append(str2); 

// concatenation using the append() method 


Length: You can get the length of a string using the length() method or the size() method.


cpp code


int len = str1.length(); 

// get length using the length() method len = str1.size();

 // get length using the size() method 


Substring: You can extract a substring from a string using the substr() method.


cpp code


std::string substr = str1.substr(1, 3);

 // extract a substring starting at index 1 and of length 3 


Comparing strings: You can compare two strings using the == operator or the compare() method.


cpp code


if (str1 == str2) // comparison using the == operator if (str1.compare(str2) == 0) // comparison using the compare() method 


These are just some basic operations that can be performed on C++ strings. 

The std::string class provides many more methods and operations for manipulating strings.