Back to C++
2025-12-206 min read

C++ <string>

Learn C++ <string> step by step with clear examples and exercises.

Why This Matters

The `` library is a vital part of C++ programming as it provides an efficient and user-friendly way to handle text data. The ability to manipulate strings as objects simplifies the process of solving real-world problems, passing interviews, and avoiding common bugs in your code. This knowledge will empower you to write cleaner, more maintainable, and easier-to-read C++ programs.

Prerequisites

Before delving into the C++ string library, it is essential to have a solid understanding of:

  1. Basic C++ syntax and programming concepts
  2. Data structures like arrays, vectors, and lists
  3. File I/O operations using streams (std::ifstream, std::ofstream)
  4. Understanding how to declare and use classes in C++
  5. Familiarity with the Standard Template Library (STL) concepts, including iterators and algorithms
  6. Comprehension of memory management in C++, such as dynamic allocation and deallocation using new and delete

Core Concept

The ` library introduces the std::string` class, which represents a sequence of characters. This class provides various member functions for manipulating strings easily. Here are some key aspects:

  1. Declaration and Initialization: To declare a string variable, use the following syntax:
std::string myString = "Hello, World!";

You can also create an empty string using std::string().

  1. Accessing Characters: Access individual characters in a string using square brackets []. Remember that indexing starts from 0:
std::string myString = "Hello, World!";
char firstChar = myString[0]; // firstChar will have the value 'H'
  1. Length: The length of a string can be obtained using the length() or size() member function:
std::string myString = "Hello, World!";
int len = myString.length(); // len will have the value 13
  1. Concatenation: To concatenate two strings, use the + operator:
std::string greeting1 = "Hello, ";
std::string greeting2 = "World!";
std::string fullGreeting = greeting1 + greeting2; // fullGreeting will have the value "Hello, World!"
  1. Substrings: To get a substring from a string, use the substr() member function:
std::string myString = "Hello, World!";
std::string subStr = myString.substr(7); // subStr will have the value "World!"
  1. Comparing Strings: To compare two strings, use the == operator:
std::string str1 = "Hello";
std::string str2 = "World";
bool isEqual = (str1 == str2); // isEqual will have the value false
  1. Iterating through Strings: You can iterate through a string using iterators:
std::string myString = "Hello, World!";
for (auto it = myString.begin(); it != myString.end(); ++it) {
char c = *it;
// Do something with the character c
}
  1. Finding Substrings: To find a substring within another string, use the find() member function:
std::string myString = "Hello, World!";
int pos = myString.find("World"); // pos will have the value 7
  1. Replacing Substrings: To replace a substring within another string, use the replace() member function:
std::string myString = "Hello, World!";
myString.replace(0, 5, "Greetings"); // myString will have the value "Greetings, World!"
  1. Comparing Strings case-insensitively: To compare two strings case-insensitively, use the compare() member function with the third argument set to std::case_insensitive:
std::string str1 = "HELLO";
std::string str2 = "hello";
int result = str1.compare(str2, std::case_insensitive); // result will have the value 0

Worked Example

Let's create a simple program that takes user input, reverses it, and prints the result:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
std::string userInput;
std::cout << "Enter a string: ";
std::getline(std::cin, userInput);

// Reverse the string using iterators and the `reverse()` algorithm
std::reverse(userInput.begin(), userInput.end());

std::cout << "Reversed string: " << userInput << std::endl;
return 0;
}

Common Mistakes

  1. **Forgetting to include the ` header**: Always remember to include the ` header at the beginning of your C++ files:
#include <string>
  1. Incorrectly accessing string elements: Make sure you're using valid indices when accessing characters in a string:
std::string myString = "Hello, World!";
char firstChar = myString[0]; // Correct
char invalidIndex = myString[14]; // Invalid index — use `size()` to get the last valid index
  1. Comparing strings with == operator: Be aware that comparing two strings using the == operator requires both strings to have the same length:
std::string str1 = "Hello";
std::string str2 = "World";
bool isEqual = (str1 == str2); // isEqual will have the value false, even though they are not equal

To correctly compare strings, use std::strcmp(), std::equal(), or compare lengths before comparing characters.

  1. Ignoring memory management: Remember that string objects in C++ dynamically allocate and deallocate memory for the contained characters. This can lead to performance issues if not managed properly:
std::string myString = "Hello, World!"; // No memory issues here
myString += " This is an example."; // Memory is reallocated to accommodate the additional characters
  1. Using raw C-style strings: While it's possible to use raw C-style strings (char*) in C++, it is generally recommended to use std::string for its convenience and built-in memory management:
// Using a raw C-style string
char* myString = "Hello, World!"; // This is not a good practice

Practice Questions

  1. Write a program that takes two strings as input and prints their concatenation.
  2. Write a program that checks whether a given string is a palindrome (reads the same forwards and backwards).
  3. Write a program that sorts an array of strings using the bubble sort algorithm.
  4. Write a program that replaces all occurrences of a specific substring in a given string.
  5. Write a program that counts the number of occurrences of a specific substring in a given string.
  6. Write a program that removes all whitespace from a given string.
  7. Write a program that reverses each word in a given sentence without changing the order of words.
  8. Write a program that capitalizes the first letter of every word in a given sentence.
  9. Write a program that finds the longest common substring between two strings.
  10. Write a program that finds all anagrams (strings with the same characters) within a given set of strings.

FAQ

  1. Why is it important to include the `` header?

Including the `` header provides access to the functions and classes defined in the C++ string library, making it possible to work with strings as objects.

  1. Can I use std::string for performance-critical applications?

While std::string offers many conveniences, it may not be the best choice for performance-critical applications due to additional overhead compared to C-style string manipulation. Use char* and related functions when performance is a concern.

  1. What happens if I try to access an invalid index in a string?

Accessing an invalid index in a string will result in undefined behavior, which can lead to program crashes or security vulnerabilities. Always ensure that your indices are within the valid range of the string.

  1. Are there any performance benefits to using std::string over C-style strings?

In many cases, std::string offers better performance than manually managing memory for C-style strings, especially when dealing with complex operations like concatenation or searching for substrings. However, for simple string manipulation and low-level programming, C-style strings may still be more efficient.

  1. What is the difference between std::string::size() and std::string::length()?

Both std::string::size() and std::string::length() return the number of characters in a string, but they may behave differently for strings that store multibyte characters. In general, it's recommended to use std::string::size(), as it is more consistent across different compilers and platforms.

  1. Why can't I assign a raw C-style string (char*) to a std::string object directly?

C++ does not allow direct assignment of a raw C-style string to a std::string object because the latter dynamically manages memory, while the former does not. To achieve this, use the std::string(const char*) constructor:

char* myString = "Hello, World!";
std::string str(myString); // Correct way to convert a raw C-style string to a std::string object
C++ &lt;string&gt; | C++ | XQA Learn