Strings (std::string) in C++
std::string is a class from the STL library that stores and manipulates text (strings). Before C++ had std::string, programmers had to use C-style strings (a char array terminated with null \0). std::string is much safer, more flexible, and easier to use.
To use std::string, include the header #include <string>. This class supports operations such as concatenation, searching, replacement, extraction, and comparison. std::string also manages memory automatically, so programmers do not need to worry about manual allocation.
Key differences between C-style strings and std::string:
- C-style string: char text[] = "Hello"; — Fixed size, prone to buffer overflow, many manual functions (strcpy, strlen, etc.).
- std::string: string text = "Hello"; — Dynamic size, the + operator for concatenation, .length() for the length, safer.
Basic String Operations
Concatenation is done with the + or += operator. Comparison uses ==, !=, <, >. The .length() or .size() method returns the string's length. The .find() method searches for a substring. The .substr() method extracts a part of a string.
Input and Output
To read input containing spaces, use getline(cin, variable). cin >> variable only reads up to the first space. getline reads the entire line, including spaces.
Code Example
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
// Creating strings
string empty;
string greet = "Hello";
string repeated(5, 'A'); // "AAAAA"
string fromChar = string("World");
cout << "Empty: \"" << empty << "\"" << endl;
cout << "Greeting: " << greet << endl;
cout << "Repeated: " << repeated << endl;
cout << "From char: " << fromChar << endl;
// Concatenation
string name = "John";
string greetFull = greet + " " + name;
cout << "\nCombined: " << greetFull << endl;
greet += " Again"; // greet is now = "Hello Again"
greet += "!";
cout << "After += : " << greet << endl;
// String length
cout << "\nLength: " << greet.length() << " (size: " << greet.size() << ")" << endl;
cout << "Is it empty? " << (empty.empty() ? "Yes" : "No") << endl;
// Accessing characters
cout << "\nFirst character: " << greet[0] << endl;
cout << "Last character: " << greet.at(greet.length() - 1) << endl;
greet[0] = 'h'; // change H to h
cout << "After modification: " << greet << endl;
// Searching
string sentence = "I like to learn C++ at home";
size_t pos = sentence.find("learn");
if (pos != string::npos) {
cout << "\nFound 'learn' at index: " << pos << endl;
} else {
cout << "\nNot found" << endl;
}
// Substring
string sub = sentence.substr(10, 5); // start at index 10, take 5 characters
cout << "Substring: " << sub << endl;
// Replace
string text = "Hello World, World Is Beautiful";
text.replace(6, 5, "Every"); // start at index 6, replace 5 characters
cout << "Replace: " << text << endl;
// Erase
text.erase(6, 6); // remove 6 characters starting at index 6
cout << "Erase: " << text << endl;
// Insert
text.insert(0, "Oh ");
cout << "Insert: " << text << endl;
// Comparison
string a = "apple";
string b = "banana";
if (a < b) {
cout << "\n'" << a << "' is smaller than '" << b << "'" << endl;
}
if (a == "apple") {
cout << "Equal to 'apple'" << endl;
}
// Input with getline
string fullName;
cout << "\nEnter your full name: ";
getline(cin, fullName);
cout << "Hello, " << fullName << "!" << endl;
// Use case: simple email validation
string email = "[email protected]";
size_t atPos = email.find('@');
size_t dotPos = email.rfind('.');
bool valid = (atPos != string::npos && dotPos != string::npos && atPos < dotPos);
cout << "\nEmail valid? " << (valid ? "Yes" : "No") << endl;
// Use case: counting vowels
string word = "programming";
int vowelCount = 0;
for (char c : word) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
cout << "Vowel count in '" << word << "': " << vowelCount << endl;
// Example: string to uppercase
string lower = "hello world";
transform(lower.begin(), lower.end(), lower.begin(), ::toupper);
cout << "Uppercase: " << lower << endl;
return 0;
}
Code Explanation
string repeated(5, 'A');— Creates a string containing 5 'A' characters, i.e. "AAAAA". This is a fill constructor.greet + " " + name— The+operator joins two or more strings. It does not modify the original strings; it returns a new string.greet += " Again"— The+=operator appends a string at the end. It modifies the original string (in-place)..length()and.size()— Both return the number of characters..size()is more common in the STL..empty()— Returnstrueif the string is empty (length 0).greet[0]— Accesses a character by index. It can be used for reading or writing..at(1)— Same as[1]but throws an out_of_range exception if the index is invalid. Safer.sentence.find("learn")— Searches for a substring and returns the index position of the first occurrence. If not found, it returnsstring::npos(a special constant).sentence.substr(10, 5)— Extracts a substring starting at index 10 with 5 characters.text.replace(6, 5, "Every")— Replaces 5 characters starting at index 6 with the string "Every".text.erase(6, 6)— Removes 6 characters starting at index 6.text.insert(0, "Oh ")— Inserts a string at the position of index 0.getline(cin, fullName)— Reads a full line of input, including spaces. Important for inputting names or sentences.transform(... ::toupper)— Converts every character to uppercase. Requires<algorithm>.email.find('@')andemail.rfind('.')—findsearches from the front,rfindfrom the back. Used together for validating an email format.
Everyday Use Cases
Online registration system: When a user signs up, their full name needs to be processed. std::string allows you to remove leading/trailing spaces, change upper/lower case, and validate input format. For example, ensuring an email contains @ and ., or ensuring a phone number contains only digits.
Other examples:
- File search: Checking whether a file name contains a particular extension with .find(".pdf").
- IoT sensor: Processing string data from sensors before storing it in a database.
- Chatbot: Processing user messages with keyword search using .find().
Conclusion
std::string is the modern and safe way to work with text in C++. Compared to C-style strings, std::string manages memory automatically, provides a rich set of methods, and supports operators such as + for concatenation and < for comparison. Always use std::string unless there is a strong reason to use a C-style string (for example, interop with a C library).