Strings C++
Strings C++
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 = expression.append(things) ;
cout << sentence;
return 0;
}
string x = "500";
string y = "25";
string z = x + y; //the result is 50025
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];
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>
int main() {
string str1 = "Hello, ";
string str2 = "world!";
string result = str1 + "C++";
return 0;
}
a) Hello, C++world!
b) Hello, C++
c) Hello, C++world!world!
d) Compilation error