C++ Strings
The string type stores text and gives you many useful functions to work with it.
Creating Strings
Include the <string> library:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string first = "Ali";
string last = "Raza";
string full = first + " " + last;
cout << full << "\n";
full += " Khan";
cout << full << "\n";
return 0;
}Ali Raza Ali Raza Khan
+ joins strings, and += adds text to the end of an existing string.
Useful String Functions
| Function | What it does |
|---|---|
s.length() or s.size() | Number of characters |
s[i] | Character at index i |
s.find("x") | Position of the first match, or string::npos |
s.substr(start, count) | Part of the string |
s.empty() | true if the string has no characters |
s.append("x") | Adds text to the end |
s.replace(pos, count, "x") | Replaces part of the string |
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string course = "Web Development";
cout << course.length() << "\n";
cout << course[0] << "\n";
cout << course.find("Dev") << "\n";
cout << course.substr(4, 3) << "\n";
course[0] = 'w';
cout << course << "\n";
return 0;
}15 W 4 Dev web Development
Indexes start at 0. In a string of length 15, the last character is at index 14.
Numbers and Strings
You cannot join a number to a string with + directly. Convert it first with to_string. To go the other way, use stoi (to int) or stod (to double):
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
int roll = 17;
string label = "Roll no " + to_string(roll);
cout << label << "\n";
string typed = "250";
int price = stoi(typed);
cout << price * 2 << "\n";
return 0;
}Roll no 17 500
Comparing Strings
Unlike C, you can compare C++ strings with ==, !=, < and >:
Example
string password = "karachi786";
string input = "karachi786";
if (password == input) {
cout << "Login successful\n";
}Login successful
< and > compare in dictionary order, so "apple" < "banana" is true.
Looping Through a String
Example
string word = "Pakistan";
int vowels = 0;
for (char ch : word) {
if (ch == 'a' || ch == 'i') {
vowels++;
}
}
cout << vowels << "\n";3
Reading a Full Line
cin >> s reads only one word. Use getline for a whole line with spaces:
Example
string address;
getline(cin, address); // e.g. Sector 11, Orangi TownExercise
Exercise
What does string("Karachi").substr(0, 3) return?
