Coming Soon
This lesson is currently being developed
Introduction to std::string
Learn to work with text strings using the standard library.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
5.7 — Introduction to std::string
In this lesson, you'll learn about std::string
, C++'s powerful class for working with text data. You'll understand how strings work, how to create and manipulate them, and why they're much easier to use than C-style character arrays.
What is std::string?
std::string
is a class provided by the C++ Standard Library that represents a sequence of characters (text). It's designed to make working with text data safe, convenient, and efficient.
Think of std::string
as a smart container for text that automatically manages memory, provides useful operations, and protects you from common string-related errors.
Why use std::string?
Before std::string
, C programmers used character arrays, which were error-prone and difficult to work with. std::string
provides many advantages:
- Automatic memory management: No need to worry about buffer sizes
- Easy concatenation: Simple string combination with
+
operator - Built-in functions: Many useful string operations included
- Safety: Bounds checking and automatic null termination
- Dynamic sizing: Strings can grow and shrink as needed
Including std::string
To use std::string
, include the <string>
header:
#include <iostream>
#include <string>
int main()
{
std::string message = "Hello, World!";
std::cout << message << std::endl;
return 0;
}
Output:
Hello, World!
Creating std::string objects
String initialization
There are several ways to create and initialize strings:
#include <iostream>
#include <string>
int main()
{
// Different ways to initialize strings
std::string empty; // Empty string
std::string greeting = "Hello"; // From string literal
std::string name("Alice"); // Constructor with string literal
std::string message = greeting; // Copy from another string
std::string repeated(5, 'X'); // 5 copies of character 'X'
std::string partial("Programming", 7); // First 7 characters of "Programming"
std::cout << "empty: '" << empty << "'" << std::endl;
std::cout << "greeting: " << greeting << std::endl;
std::cout << "name: " << name << std::endl;
std::cout << "message: " << message << std::endl;
std::cout << "repeated: " << repeated << std::endl;
std::cout << "partial: " << partial << std::endl;
return 0;
}
Output:
empty: ''
greeting: Hello
name: Alice
message: Hello
repeated: XXXXX
partial: Program
String assignment
You can assign new values to strings:
#include <iostream>
#include <string>
int main()
{
std::string text;
text = "First value";
std::cout << "After first assignment: " << text << std::endl;
text = "Second value";
std::cout << "After second assignment: " << text << std::endl;
std::string other = "From another string";
text = other;
std::cout << "After copying from other: " << text << std::endl;
return 0;
}
Output:
After first assignment: First value
After second assignment: Second value
After copying from other: From another string
Basic string operations
String length
Use length()
or size()
to get the number of characters:
#include <iostream>
#include <string>
int main()
{
std::string text = "Hello, World!";
std::cout << "Text: " << text << std::endl;
std::cout << "Length: " << text.length() << std::endl;
std::cout << "Size: " << text.size() << std::endl; // Same as length()
// Check if string is empty
std::string empty;
std::cout << "Empty string length: " << empty.length() << std::endl;
std::cout << "Is empty: " << empty.empty() << std::endl;
return 0;
}
Output:
Text: Hello, World!
Length: 13
Size: 13
Empty string length: 0
Is empty: 1
String concatenation
Use the +
operator to combine strings:
#include <iostream>
#include <string>
int main()
{
std::string first = "Hello";
std::string second = "World";
std::string space = " ";
std::string exclamation = "!";
// Concatenation with + operator
std::string greeting = first + ", " + second + exclamation;
std::cout << "Greeting: " << greeting << std::endl;
// Concatenation with += operator
std::string message = "Good";
message += " ";
message += "morning";
message += "!";
std::cout << "Message: " << message << std::endl;
// Mixing strings and string literals
std::string name = "Alice";
std::string welcome = "Welcome, " + name + "!";
std::cout << "Welcome: " << welcome << std::endl;
return 0;
}
Output:
Greeting: Hello, World!
Message: Good morning!
Welcome: Welcome, Alice!
Accessing individual characters
Use the subscript operator []
or at()
to access characters:
#include <iostream>
#include <string>
int main()
{
std::string text = "Programming";
std::cout << "Text: " << text << std::endl;
std::cout << "First character: " << text[0] << std::endl;
std::cout << "Last character: " << text[text.length() - 1] << std::endl;
// Using at() method (safer - throws exception if out of bounds)
std::cout << "Third character: " << text.at(2) << std::endl;
// Modify individual characters
text[0] = 'p'; // Change 'P' to 'p'
std::cout << "After modification: " << text << std::endl;
// Print all characters with their positions
std::cout << "Character by character:" << std::endl;
for (size_t i = 0; i < text.length(); ++i)
{
std::cout << "Position " << i << ": '" << text[i] << "'" << std::endl;
}
return 0;
}
Output:
Text: Programming
First character: P
Last character: g
Third character: o
After modification: programming
Character by character:
Position 0: 'p'
Position 1: 'r'
Position 2: 'o'
Position 3: 'g'
Position 4: 'r'
Position 5: 'a'
Position 6: 'm'
Position 7: 'm'
Position 8: 'i'
Position 9: 'n'
Position 10: 'g'
String comparison
You can compare strings using comparison operators:
#include <iostream>
#include <string>
int main()
{
std::string str1 = "apple";
std::string str2 = "banana";
std::string str3 = "apple";
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str3: " << str3 << std::endl;
// Equality comparison
std::cout << "\nEquality comparisons:" << std::endl;
std::cout << "str1 == str2: " << (str1 == str2) << std::endl;
std::cout << "str1 == str3: " << (str1 == str3) << std::endl;
std::cout << "str1 != str2: " << (str1 != str2) << std::endl;
// Lexicographic comparison
std::cout << "\nLexicographic comparisons:" << std::endl;
std::cout << "str1 < str2: " << (str1 < str2) << std::endl; // apple < banana
std::cout << "str1 > str2: " << (str1 > str2) << std::endl; // apple > banana
std::cout << "str2 > str1: " << (str2 > str1) << std::endl; // banana > apple
// Comparison with string literals
std::cout << "\nComparison with literals:" << std::endl;
std::cout << "str1 == \"apple\": " << (str1 == "apple") << std::endl;
std::cout << "str1 == \"Apple\": " << (str1 == "Apple") << std::endl; // Case sensitive
return 0;
}
Output:
str1: apple
str2: banana
str3: apple
Equality comparisons:
str1 == str2: 0
str1 == str3: 1
str1 != str2: 1
Lexicographic comparisons:
str1 < str2: 1
str1 > str2: 0
str2 > str1: 1
Comparison with literals:
str1 == "apple": 1
str1 == "Apple": 0
String input and output
Reading strings from input
#include <iostream>
#include <string>
int main()
{
std::string name;
std::string message;
std::cout << "Enter your name: ";
std::cin >> name; // Reads until whitespace
std::cout << "Hello, " << name << "!" << std::endl;
// To read a line with spaces, use getline
std::cout << "Enter a message: ";
std::cin.ignore(); // Clear the newline from previous input
std::getline(std::cin, message);
std::cout << "Your message: " << message << std::endl;
return 0;
}
Example interaction:
Enter your name: Alice
Hello, Alice!
Enter a message: Hello, how are you?
Your message: Hello, how are you?
Formatted string output
#include <iostream>
#include <string>
int main()
{
std::string firstName = "John";
std::string lastName = "Smith";
int age = 25;
double height = 5.9;
// Simple output
std::cout << "Name: " << firstName << " " << lastName << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Height: " << height << " feet" << std::endl;
// More complex formatting
std::cout << "\nFormatted information:" << std::endl;
std::cout << "Full name: " << firstName + " " + lastName << std::endl;
std::cout << "Profile: " << firstName << " is " << age
<< " years old and " << height << " feet tall." << std::endl;
return 0;
}
Output:
Name: John Smith
Age: 25
Height: 5.9 feet
Formatted information:
Full name: John Smith
Profile: John is 25 years old and 5.9 feet tall.
Common string methods
substr() - Getting substrings
#include <iostream>
#include <string>
int main()
{
std::string text = "Hello, World!";
std::cout << "Original: " << text << std::endl;
// Extract substrings
std::string hello = text.substr(0, 5); // From position 0, length 5
std::string world = text.substr(7, 5); // From position 7, length 5
std::string fromSeven = text.substr(7); // From position 7 to end
std::cout << "First 5 characters: " << hello << std::endl;
std::cout << "Characters 7-11: " << world << std::endl;
std::cout << "From position 7: " << fromSeven << std::endl;
return 0;
}
Output:
Original: Hello, World!
First 5 characters: Hello
Characters 7-11: World
From position 7: World!
find() - Finding substrings
#include <iostream>
#include <string>
int main()
{
std::string text = "The quick brown fox jumps over the lazy dog";
std::cout << "Text: " << text << std::endl;
// Find substrings
size_t pos1 = text.find("fox");
size_t pos2 = text.find("cat");
size_t pos3 = text.find("the"); // Finds first occurrence
size_t pos4 = text.find("the", 20); // Find starting from position 20
std::cout << "Position of 'fox': ";
if (pos1 != std::string::npos)
std::cout << pos1 << std::endl;
else
std::cout << "not found" << std::endl;
std::cout << "Position of 'cat': ";
if (pos2 != std::string::npos)
std::cout << pos2 << std::endl;
else
std::cout << "not found" << std::endl;
std::cout << "First 'the' at position: " << pos3 << std::endl;
std::cout << "Next 'the' after position 20: " << pos4 << std::endl;
return 0;
}
Output:
Text: The quick brown fox jumps over the lazy dog
Position of 'fox': 16
Position of 'cat': not found
First 'the' at position: 0
Next 'the' after position 20: 31
replace() - Replacing parts of strings
#include <iostream>
#include <string>
int main()
{
std::string text = "I love programming in Java";
std::cout << "Original: " << text << std::endl;
// Replace "Java" with "C++"
size_t pos = text.find("Java");
if (pos != std::string::npos)
{
text.replace(pos, 4, "C++"); // Replace 4 characters starting at pos
}
std::cout << "After replacement: " << text << std::endl;
// Replace multiple occurrences
std::string poem = "roses are red, violets are blue";
std::cout << "Poem: " << poem << std::endl;
// Replace "are" with "were"
pos = 0;
while ((pos = poem.find("are", pos)) != std::string::npos)
{
poem.replace(pos, 3, "were");
pos += 4; // Move past the replacement
}
std::cout << "Modified poem: " << poem << std::endl;
return 0;
}
Output:
Original: I love programming in Java
After replacement: I love programming in C++
Poem: roses are red, violets are blue
Modified poem: roses were red, violets were blue
Practical string examples
Name processing
#include <iostream>
#include <string>
int main()
{
std::string fullName = "Alice Johnson Smith";
std::cout << "Full name: " << fullName << std::endl;
// Extract first name
size_t firstSpace = fullName.find(' ');
std::string firstName = fullName.substr(0, firstSpace);
// Extract last name
size_t lastSpace = fullName.find_last_of(' ');
std::string lastName = fullName.substr(lastSpace + 1);
// Extract middle name
std::string middleName;
if (firstSpace != lastSpace) // There is a middle name
{
middleName = fullName.substr(firstSpace + 1, lastSpace - firstSpace - 1);
}
std::cout << "First name: " << firstName << std::endl;
std::cout << "Middle name: " << middleName << std::endl;
std::cout << "Last name: " << lastName << std::endl;
// Create initials
std::string initials;
initials += firstName[0];
if (!middleName.empty())
{
initials += middleName[0];
}
initials += lastName[0];
std::cout << "Initials: " << initials << std::endl;
return 0;
}
Output:
Full name: Alice Johnson Smith
First name: Alice
Middle name: Johnson
Last name: Smith
Initials: AJS
Simple text processing
#include <iostream>
#include <string>
int main()
{
std::string text = "The quick brown fox jumps over the lazy dog.";
std::cout << "Original text: " << text << std::endl;
std::cout << "Length: " << text.length() << " characters" << std::endl;
// Count words (simple method - count spaces + 1)
int wordCount = 1;
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == ' ')
wordCount++;
}
std::cout << "Word count: " << wordCount << std::endl;
// Count specific characters
int letterA = 0;
int letterO = 0;
for (size_t i = 0; i < text.length(); ++i)
{
if (text[i] == 'a' || text[i] == 'A')
letterA++;
if (text[i] == 'o' || text[i] == 'O')
letterO++;
}
std::cout << "Letter 'a' count: " << letterA << std::endl;
std::cout << "Letter 'o' count: " << letterO << std::endl;
// Check if text contains specific words
std::cout << "Contains 'fox': " << (text.find("fox") != std::string::npos) << std::endl;
std::cout << "Contains 'cat': " << (text.find("cat") != std::string::npos) << std::endl;
return 0;
}
Output:
Original text: The quick brown fox jumps over the lazy dog.
Length: 44 characters
Word count: 9
Letter 'a' count: 1
Letter 'o' count: 4
Contains 'fox': 1
Contains 'cat': 0
Building formatted strings
#include <iostream>
#include <string>
int main()
{
// Student information
std::string studentName = "Emma Wilson";
int studentAge = 20;
std::string major = "Computer Science";
double gpa = 3.75;
int creditsCompleted = 85;
// Build a formatted report
std::string report = "STUDENT REPORT\n";
report += "==============\n";
report += "Name: " + studentName + "\n";
report += "Age: " + std::to_string(studentAge) + " years old\n";
report += "Major: " + major + "\n";
report += "GPA: " + std::to_string(gpa) + "\n";
report += "Credits Completed: " + std::to_string(creditsCompleted) + "\n";
// Add status based on credits
std::string status;
if (creditsCompleted >= 90)
status = "Senior";
else if (creditsCompleted >= 60)
status = "Junior";
else if (creditsCompleted >= 30)
status = "Sophomore";
else
status = "Freshman";
report += "Class Status: " + status + "\n";
// Add GPA assessment
std::string assessment;
if (gpa >= 3.5)
assessment = "Excellent";
else if (gpa >= 3.0)
assessment = "Good";
else if (gpa >= 2.5)
assessment = "Satisfactory";
else
assessment = "Needs Improvement";
report += "Academic Standing: " + assessment + "\n";
std::cout << report << std::endl;
return 0;
}
Output:
STUDENT REPORT
==============
Name: Emma Wilson
Age: 20 years old
Major: Computer Science
GPA: 3.750000
Credits Completed: 85
Class Status: Junior
Academic Standing: Excellent
Best practices for std::string
1. Use string literals efficiently
#include <iostream>
#include <string>
int main()
{
// Good: Direct initialization
std::string message = "Hello, World!";
// Good: Efficient concatenation
std::string name = "Alice";
std::string greeting = "Hello, " + name + "!";
// Good: Use += for multiple concatenations
std::string longMessage = "This is ";
longMessage += "a long ";
longMessage += "message ";
longMessage += "built efficiently.";
std::cout << message << std::endl;
std::cout << greeting << std::endl;
std::cout << longMessage << std::endl;
return 0;
}
2. Check bounds when necessary
#include <iostream>
#include <string>
int main()
{
std::string text = "Hello";
// Safe access using at()
try
{
std::cout << "Character at position 2: " << text.at(2) << std::endl;
std::cout << "Character at position 10: " << text.at(10) << std::endl; // Will throw
}
catch (const std::out_of_range& e)
{
std::cout << "Error: " << e.what() << std::endl;
}
// Check string length before accessing
int position = 10;
if (position < static_cast<int>(text.length()))
{
std::cout << "Character at position " << position << ": " << text[position] << std::endl;
}
else
{
std::cout << "Position " << position << " is out of bounds" << std::endl;
}
return 0;
}
3. Use const when appropriate
#include <iostream>
#include <string>
// Function that doesn't modify the string
void printStringInfo(const std::string& text)
{
std::cout << "String: " << text << std::endl;
std::cout << "Length: " << text.length() << std::endl;
std::cout << "Empty: " << (text.empty() ? "Yes" : "No") << std::endl;
}
int main()
{
const std::string message = "Hello, World!";
printStringInfo(message);
return 0;
}
Output:
String: Hello, World!
Length: 13
Empty: No
Summary
std::string
is a powerful and convenient way to work with text in C++:
- Easy to use: Simple syntax for creation, assignment, and manipulation
- Safe: Automatic memory management and bounds checking options
- Flexible: Dynamic sizing and many built-in operations
- Efficient: Optimized for common string operations
- Standard: Part of the C++ Standard Library, available everywhere
Key operations include:
- Creating and initializing strings
- Concatenation with
+
and+=
- Accessing characters with
[]
andat()
- Getting length with
length()
orsize()
- Finding substrings with
find()
- Extracting parts with
substr()
- Replacing content with
replace()
std::string
makes text processing much easier and safer than traditional C-style strings, and it's the standard way to handle text in modern C++.
Quiz
- What header file do you need to include to use
std::string
? - What's the difference between
length()
andsize()
methods? - How do you check if a string is empty?
- What does
find()
return if the substring is not found? - What's the difference between
[]
andat()
for accessing characters?
Practice exercises
Try these string exercises:
- Write a program that takes a full name and formats it as "Last, First"
- Create a simple word counter that counts words, characters, and vowels in a string
- Write a program that reverses a string without using built-in reverse functions
- Create a simple find-and-replace program that replaces all occurrences of one word with another
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions