A String is a collection of letters/alphabets. It can be a word or a sentence.
The Data Type for String is string.
When C++ finds data inside Double Quotes "" and of datatype string. It creates a String type variable for that value.
string x = "Hello World";
#include <iostream> using namespace std; int main() { string x = "Hello World"; cout << x; return 0; }
And that's all! You have a String in place.
Let us understand the next example with the below code.
#include <iostream> using namespace std; int main() { string x; x = "Hello World"; cout << x; return 0; }
Just note that we have not initialised the variable x. We have just declared it.
string x;
So that an empty variable x would be created that would only hold a String.
Then in the next line, we have assigned the value Hello World to the variable x.
x = "Hello World";
Well ! We have declared a String type variable and assigned it later.
#include <iostream> using namespace std; int main() { string x = "Hello"; char y = x[1]; cout << y; return 0; }
So, we have a string Hello,
string x = "Hello";
And we have assigned Hello to a variable x.
Let us elaborate more, on how the String Hello is stored in the variable x.
So, just for the sake of understanding, you can assume the variable x is divided into 5 parts to store Hello.
Now, if you check from the front, the count starts from 0 and ends with 4.
So, if we look at the next line in the code,
char y = x[1];
We are trying to access the 2nd location,
So, x[1] is referring to the 2nd location where e is stored.
char y = x[1];
And we have assigned e to the variable y.
Now, if you look at the print statement,
cout << y;
The value of y is printed as output.
In the earlier examples, we have seen the + sign. And as we know, + is used for addition of two numbers.
Well ! In C++, + can be used to join two Strings as well.
Say, we have two Strings, Hello and World. And we want to join/concatenate them into one String, HelloWorld.
Let us solve it with the below example.
#include <iostream> using namespace std; int main() { string x = "Hello"; string y = "World"; string z = x + y; cout << z; return 0; }
So, we have stored the String Hello in x.
string x = "Hello";
And, stored the String World in y.
string y = "World";
And used the + operator to join/concatenate Hello and World.
string z = x + y;
And store the concatenated value in z.
So, + is not just used to add two numbers but + is also used to join/concatenate two Strings.
size() is used to return the length of a String.
#include <iostream> using namespace std; int main() { string x = "Hello"; cout << "The length of the String is : " << x.size(); return 0; }
length() is used to return the length of a String.
#include <iostream> using namespace std; int main() { string x = "Hello"; cout << "The length of the String is : " << x.length(); return 0; }