Tutorials › C++ › Strings
Beginner 8 min read Lesson 11 of 50
Creating Strings
In C++, a string is an object of the std::string class. Include <string> to use it (often available via <iostream>).
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello, World!";
cout << greeting << endl;
cout << "Length: " << greeting.length() << endl;
return 0;
}
Output:
Hello, World!
Length: 13
String Concatenation
Use the + operator to join strings:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName; // John Doe
Useful String Methods
Method Description Example
.length()Returns the number of characters s.length()
.size()Same as length() s.size()
.toupper()Use with <algorithm> transform(...)
.find()Finds a substring s.find("lo")
.substr()Extracts a substring s.substr(0,5)
.erase()Removes characters s.erase(0,3)
.replace()Replaces a substring s.replace(0,5,"Hi")
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello, World!";
cout << s.length() << endl; // 13
cout << s.substr(7, 5) << endl; // World
cout << s.find("World") << endl; // 7
s.replace(7, 5, "C++");
cout << s << endl; // Hello, C++!
return 0;
}
Accessing Characters
string s = "Hello";
cout << s[0]; // H
cout << s[4]; // o
cout << s.at(1); // e (safe, throws if out of range)
Exercise
Write a program that reads a string from the user and prints: its length, the first character, the last character, and the string reversed using a loop.
Show Solution
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout << "Enter a word: ";
cin >> s;
cout << "Length: " << s.length() << endl;
cout << "First: " << s[0] << endl;
cout << "Last: " << s[s.length()-1] << endl;
cout << "Reversed: ";
for (int i = s.length()-1; i >= 0; i--) cout << s[i];
cout << endl;
return 0;
}
Quiz
Which method returns the number of characters in a C++ string?
A) count() B) size() C) chars() D) len() Answer B) size() (also length() — both work identically).
Which operator concatenates two strings?
Answer C) +
Summary
string is a class from the <string> header.
Concatenate with +; access characters with [i] or .at(i).
Key methods: length(), substr(), find(), replace().