Index
C++ Strings
Strings are used for storing text. A string
variable contains a collection of characters surrounded by double quotes:
Example:
Create a variable of type string
and assign it a value:
string greeting = "Hello";
To use strings, you must include an additional header file in the source code, the <string>
library:
Example:
// Include the string library
#include <string>
// Create a string variable
string greeting = "Hello";
String Concatenation
The +
operator can be used between strings to add them together to make a new string. This is called concatenation:
Example:
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Marcos";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
Output:
John Marcos
In the example above, we added a space after firstName to create a space between John and Doe on output. However, you could also add a space with quotes (" "
or ' '
):
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John";
string lastName = "Marcos";
string fullName = firstName + " " + lastName;
cout << fullName;
return 0;
}
Output:
John Marcos
Append
In C++, “append” typically refers to adding elements to the end of a container, such as a vector, string, or list. Here’s how you can append elements to various containers in C++:
Example:
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Marcos";
string fullName = firstName.append(lastName);
cout << fullName;
return 0;
}
Output:
John Marcos
Numbers and Strings
Adding Numbers and Strings
WARNING! C++ uses the +
operator for both addition and concatenation. Numbers are added. Strings are concatenated. If you add two numbers, the result will be a number:
Example:
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
If you add two strings, the result will be a string concatenation:
Example:
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)
If you try to add a number to a string, an error occurs:
Example:
string x = "10";
int y = 20;
string z = x + y; //ERROR
String Length
To get the length of a string, use the length()
function:
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
return 0;
}
Output:
The length of the txt string is: 26
Tip: In C++, size()
and length()
are essentially interchangeable when it comes to getting the length of a string. Both functions serve the same purpose and return the number of characters in the string. size()
is simply an alias for length()
, provided for convenience and consistency with other standard library containers like vectors and lists.
So, whether you use size()
or length()
is entirely a matter of personal preference or coding style. You can choose whichever one you find more readable or intuitive. Both will give you the same result.
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
return 0;
}
Output:
The length of the txt string is: 26
Access String
You can access the characters in a string by referring to its index number inside square brackets []
.
This example prints the first character in myString:
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
cout << myString[1];
return 0;
}
Output:
e
Change String Characters
To change the value of a specific character in a string, refer to the index number, and use single quotes:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
myString[0] = 'J';
cout << myString;
return 0;
}
Output:
Jello
User Input Strings
It is possible to use the extraction operator >>
on cin
to store a string entered by a user:
Example:
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: Daniyal
// Your name is: Daniyal
However, cin
considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only store a single word (even if you type many words):
Example:
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
// Type your full name: Daniyal khan
// Your name is: Daniyal khan
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:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
Omitting Namespace
In C++, you can access entities from the standard namespace (std
) without explicitly bringing them into scope using the using namespace std
directive. Instead, you can prefix standard library entities with std::
to specify their namespace explicitly. This approach avoids potential namespace clashes and keeps the code more readable and maintainable.
Here’s an example illustrating how to use std::
to access string
and cout
without relying on using namespace std
:
Example:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
Output:
Hello