I.
Strings
A string variable contains a collection of characters surrounded by double quotes (or in short: a
word or sentence)
You must include <string> library as a header file in order to use strings.
Example:
#include <string>
using namespace std;
int main(){
string expression = "Aaaaahhh!";
return 0;
II. Concatenation
The “+” operator can be used between strings to add them together to make a new string. This is
called concatenation. You can also create a blank string using ‘ ‘ or “ “.
#include <string>
#include <iostream>
using namespace std;
int main(){
string expression = "Aaaaahhh!";
string things = "Ghost!!";
string sentence = expression + " " + things;
cout << sentence;
return 0;
}
You can use append() to concatenate a string to the back of the original string too.
#include <string>
#include <iostream>
using namespace std;
int main(){
string expression = "Aaaaahhh!";
string things = "Ghost!!";
string sentence = [Link](things) ;
cout << sentence;
return 0;
}
III. Number and Strings
In C++, “+” can be used on both numbers and strings. However, they serve different methods:
addition and concatenation:
int x =500;
int y =25;
int z = x + y; //the result is 525
string x = "500";
string y = "25";
string z = x + y; //the result is 50025
IV. Length of strings
To find the length of a string, we can use length.() or size.(). They both function in the same way.
string expression = "Aaaaahhh!";
cout << [Link]();
V. String’s accessibility
Strings can be generally “described” as “an array of characters”. And as in array, we use [] to
access to its element. We can do the same as a string.
string word = "abysmal";
cout << word[2];
VI. Special strings
Because strings must be written within quotes, C++ will misunderstand this string, and generate
an error when we use “” in our string. Using backslash escape character is a great way to resolve
this matter. The backslash (\) escape character turns special characters into string characters:
string word = "\"abyssmal\" means extremely bad or very deep. ";
cout << word;
The backslash (\n) and (\t) can be used to create a new line and a new tab respectively.
string word = "\"abyssmal\" means extremely bad or very deep. ";
cout << word << "\n";
VII. Multiple choice question.
What is the output of this strings?
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello, ";
string str2 = "world!";
string result = str1 + "C++";
cout << result << endl;
result = result + str2;
cout << result << endl;
return 0;
}
a) Hello, C++world!
b) Hello, C++
c) Hello, C++world!world!
d) Compilation error