08 Feb C++ Strings
An array of characters in C++ is called a string. The null character also has a role in C++. A string is terminated by a null character, i.e., \0. In this lesson, we will learn how to work with strings in C++.
Let’s first see what we meant by strings. The following is a string,
1 2 3 |
Virat |
We will now learn how to declare and initialize the above string in C++:
1 2 3 |
char celeb[] = "Virat"; |
We haven’t added the null character above, since the compiler adds it on its own. In addition, we haven’t added size, since it is optional. Let’s see the entire example.
Let’s see an example to create a string in C++:
1 2 3 4 5 6 7 8 9 10 11 |
// Create a string in C++ #include <iostream> using namespace std; int main() { char celeb[] = "Virat"; cout << "Name of the celebrity: " << celeb << endl; return 0; } |
Here is the output:
1 2 3 |
Name of the celebrity: Virat |
You can also declare and initialize the above string like the following, with extra space for the null character and size in square brackets:
1 2 3 |
char celeb[6] = {'V', 'i', 'r', 'a', 't','\0'}; |
Above, we added an extra size for the array to hold a null character.
Now let’s see another example of a string,
1 2 3 |
Studyopedia |
The declaration and initialization of the above string,
1 2 3 |
char website[] = {'S', 't', 'u', 'd', 'y', 'o', 'p', 'e', 'd', 'i', 'a','\0'}; |
You may have noticed the following in the above declaration,
- We have not added the size, since it is optional.
- A null character is added at the end.
Let’s see the entire example:
1 2 3 4 5 6 7 8 9 10 11 12 |
// Create a string in C++ with an alternative way #include <iostream> using namespace std; int main() { char website[] = {'S','t','u','d', 'y','o','p','e','d', 'i','a','\0'}; cout << "Learning website for free tutorials: " << website << endl; return 0; } |
Here is the output:
1 2 3 |
Learning website for free tutorials: Studyopedia |
The array looks like the following with characters,
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments