STRING
STRING
A string in C++ is an object that represents a sequence of characters. On the other hand, a string
in C is represented by an array of characters. C++ supports the C-style strings as well. The string
objects in C++ are more frequently used compared to the character arrays because the string
objects support a wide range of built-in functions.
Scope of Article
We will cover the different ways of defining strings in C++.
We will understand how to take string inputs from the users.
We will also cover the different functions which can be used on strings.
Syntax
The syntax to create a string in C++ is quite simple. We use the string keyword to create a string
in C++. However, we also need to include the standard string class in our program before using
this keyword.
Besides the method described above, C++ strings can be created in many different ways. The
alternative ways of defining a string are explained in the upcoming sections. Before that, let us
have a brief introduction to the C Style Character Strings.
Syntax
We can create the C style strings just like we create an integer array. Here is its syntax.
char str_array[7] = {'S', 'c', 'a', 'l', 'e', 'r', '\0'};
Because we also have to add a null character in the array, the array's length is one greater than
the length of the string. Alternatively, we can define the above string like this as well:
The array str_array will still hold 7 characters because C++ automatically adds a null character
at the end of the string. If we use the sizeof() function to check the size of the array above, it will
return 7 as well.
Using the string keyword is the best and the most convenient way of defining a string.
We should prefer using the string keyword because it is easy to write and understand.
string str_name = "hello";
// or
string str_name("hello");
Then we have the C style strings. Here are the different ways to create C style strings:
char str_name[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
// or
char str_name[] = {'h', 'e', 'l', 'l', 'o', '\0'};
Alternatively, we have:
#include <iostream>
using namespace std;
int main() {
char str[30];
return 0;
}
Input:
Output:
In the above example, the user entered "New Delhi" in the input. As " " is the terminating
character, anything written after " " was discarded. Hence, we got "New" as the output.
In order to counter this limitation of the extraction operator, we can specify the maximum
number of characters to read from the user's input using the cin.get() function.
#include <iostream>
using namespace std;
int main() {
char str[50];
cout << "You have entered: " << str << endl;
return 0;
}
Input:
Output:
Now, we were able to get the whole string entered by the user.
Apart from this method, we can also use the getline() function. The getline() function is
explained below in this article.