C Strings
C Strings
Example
String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:
Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
String Length
Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
Access Strings
You can access the characters in a string by referring to its index number
inside square brackets [].
Because strings must be written within quotes, C++ will misunderstand this
string, and generate an error:
string txt = "We are the so-called "Vikings" from the north.";
The backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
string txt = "We are the so-called \"Vikings\" from the north.";
Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
From the example above, you would expect the program to print "John Doe",
but it only prints "John".
That's why, when working with strings, we often use the getline() function
to read a line of text. It takes cin as the first parameter, and the
string variable as second:
Example
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;