Operator Overloading Application: String Class
Learn about the C++ string library, which empowers developers with efficient string manipulation capabilities, including the application of operator overloading.
We'll cover the following...
The <string> library
The string class in the C++ Standard Library provides a powerful tool for working with strings in C++. It offers a wide range of functionality for string manipulation and handling. This code snippet demonstrates some of the essential features and operations that can be performed using the string class.
This code demonstrates various operations and functionalities provided by the <string> library in C++ STL. Here’s a breakdown of how the code works:
-
Lines 7–8 (String initialization): Two strings,
str1andstr2, are initialized with the valuesHelloandWorld, respectively. -
Lines 11–12 (Concatenation): The strings
str1andstr2are concatenated using the+operator, and the result is stored instr3. -
Line 15 (String length): The
length()function is used to determine the length ofstr3. -
Lines 20–21 (Accessing individual characters): The individual characters of
str3are accessed using the[]operator. -
Line 24 (Substring extraction): The
substr()function is used to extract a substring fromstr3, starting at index6with a length of5. -
Comparison: In line 29-32:
str3is compared withstr4using the==operator to check if they are equal and the output is displayed based on the result of that comparison. -
Lines 37–40 (Relational operators): The strings
str5andstr6are compared using the<operator to determine if one string is less than the other, and the output is displayed based on the result of that comparison. -
Lines 43–44 (Assignment): The string
str3is assigned tostr7using the=operator andstr7is displayed using thecoutstatement. -
Lines 47–48 (Clearing the string): The
clear()function is called onstr7to remove its contents. -
Lines 51–53 (Appending strings): The
+=operator is used to append the stringWorldtostr8. -
Lines 56–62 (Finding substrings): The
find()function is used to search for the substringWorldwithinstr9. -
Lines 65–67 (Replacing substrings): The
replace()function is used to replace a portion ofstr10starting at index6with the stringUniverse. -
Lines 70–72 (Erasing characters): The
erase()function is used to remove a portion ofstr11starting at index5with a length of6. -
Line 75–77 (Converting an integer into a string): The
to_string()function is used to convert an integer (num) into a string (strNum). -
Lines 80–83 (Using
getline()to read a line of text): Thegetline()function is used to read a line of text from the user and store it in the string variable input. -
Lines 87–88 (Substring extraction): The
substr()function is used to extract a substring (substring) from the original string (original).