In C++, strings are not a built-in data type, instead they are a class defined in the standard template library (STL). The C++ string class, also known as std::string
, provides a lot of inbuilt functions that make string manipulation very easy. String class objects can be used much like a character array.
Creating a String
There are several ways to create a string in C++:
- Using a string literal:
string str1 = "Hello, World!";
- Using a character array:
char char_array[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'}; string str2(char_array, sizeof(char_array));
- Using a constructor:
string str3(str1); string str4(str1, 6); // "World!" string str5(5, 'a'); // "aaaaa"
String Concatenation
In C++, we can concatenate two strings using the +
operator or the +=
operator.
string str1 = "Hello, "; string str2 = "World!"; string str3 = str1 + str2; // "Hello, World!" str1 += str2; // "Hello, World!"
String Comparison
In C++, we can compare two strings using the ==
, !=
, <
, >
, <=
, and >=
operators. The comparison is based on the lexicographic order.
string str1 = "Hello"; string str2 = "World"; cout << (str1 == str2) << endl; // 0 cout << (str1 != str2) << endl; // 1 cout << (str1 < str2) << endl; // 1
String Length
In C++, we can find the length of a string using the length()
function or the size()
function.
string str = "Hello, World!"; cout << str.length() << endl; // 13 cout << str.size() << endl; // 13
String Substring
In C++, we can extract a substring from a string using the substr()
function.
string str = "Hello, World!"; cout << str.substr(0, 5) << endl; // "Hello" cout << str.substr(7, 6) << endl; // "World!"
Conclusion
C++ strings are a powerful and flexible tool for working with text data. They offer a wide range of useful functions and operators for manipulating and manipulating strings, making it easy to work with text data in C++. Whether you are working on a large project or a small script, understanding and utilizing the capabilities of C++ strings is essential for any C++ developer.