Introducing String Data Type
Learn to declare, initialize, and handle the strings.
The string data type
C++ is built on C, and it provides a data type that is defined in the namespace std and requires string as a header file.
C++ simplifies string manipulation in several ways. It even simplifies the declaration of a string over cstring so that there is no need to declare it as an array (it abstracts out that detail inside it).
Let’s practice how to use the string as a data type.
string variable: Declaration and printing
Here’s the code for declaring several kinds of simple initialization:
Printing the string is like printing the variable, it gives the effect of just like a simple variable of any primitive data type (int, char, double, etc.).
Traversing in string
The string variable can easily be traversed through just like an array. Here’s a sample example:
The dot operator (
.) in C++ is used to access the members (where a member could be another variable or a function) of an. For example, to use the function object a non-primitive variable that in itself contains primitive or non-primitive variables or functions getline()withcin, we use the dot operator just as we use the dot operator to use thesize()operator.
Reassigning a string
The strings can be re-assigned without any loop of copying:
Concatenating the strings
Concatenating is very easy, you can even expand or shrink the array, it does automatically over reassignment:
Instruction: Add the following code in the above playground.
Comparison of the strings
Comparing the strings is relatively easy. The character stored inside the strings is compared based on lexicographic order (the word which appears in the English dictionary first is considered lower in rank as compared to the word which appears later). Here are a few examples of these comparisons:
Taking string from the console or file stream
We can easily take the input from the console or from a file, just like taking any variable.
Reading from the console through cin>> (or ifstream Rdr through Rdr>>) will ignore all the spaces in the beginning and then keep reading characters one by one and concatenate them inside a variable until it finds a delimiter character such as {' ', '\t', '\n', '\r'}.
Look at the code snippet below, where we take two inputs from the user through cin and store them inside c and d and display them:
Reading through the getline() function
We can use the getline() function to read a string with a delimiter character as input.
Here’s the testing program:
Instruction: Add the following strings inside the input textbox above:
Complete implementation
Here’s the complete code of the above-mentioned examples: