C++ string
Working with text and string operations in C++
📝 What is string?
The string class in C++ provides a convenient way to work with text data. It offers many built-in functions for string manipulation, searching, and formatting operations.
#include <string>
#include <iostream>
using namespace std;
int main() {
string message = "Hello, C++ Strings!";
cout << message << endl;
return 0;
}
Output:
Hello, C++ Strings!
String Operations
Concatenation
Joining strings together
string first = "Hello";
string second = " World";
string result = first + second;
Length & Size
Getting string dimensions
string text = "Hello";
int len = text.length();
int size = text.size();
Search & Find
Finding substrings and characters
string text = "Hello World";
int pos = text.find("World");
// pos = 6
Substring
Extracting parts of strings
string text = "Hello World";
string part = text.substr(0, 5);
// part = "Hello"
🔹 Basic String Operations
The C++ std::string class, from the <string> library, provides a rich set of
member functions for safe and convenient text manipulation. Key operations include
.length() or .size() to get the number of characters, .at() or the
[] operator for safe character access, and .empty() to check if a string is empty. Unlike
C-style character arrays, std::string handles its own memory management, automatically resizing as
needed. This makes it the preferred choice for most text-processing tasks, from simple message display to complex
parsing.
#include <string>
#include <iostream>
using namespace std;
int main() {
// Creating strings
string greeting = "Hello";
string name = "Alice";
// String concatenation
string message = greeting + ", " + name + "!";
cout << "Message: " << message << endl;
// String length
cout << "Length of message: " << message.length() << endl;
cout << "Size of message: " << message.size() << endl;
// Accessing characters
cout << "First character: " << message[0] << endl;
cout << "Last character: " << message[message.length()-1] << endl;
// Check if string is empty
string empty = "";
cout << "Is empty string empty? " << empty.empty() << endl;
return 0;
}
Output:
Message: Hello, Alice!
Length of message: 13
Size of message: 13
First character: H
Last character: !
Is empty string empty? 1
🔹 String Search and Find
Searching within strings is a common requirement, and C++ provides several methods like find()
and rfind() to locate substrings or characters. The find() method returns the
index of the first occurrence of a substring (or string::npos if not found), while rfind()
searches from the end. These methods are case-sensitive and essential for tasks like parsing URLs, extracting data
from logs, validating input formats (e.g., checking for an '@' in an email), or implementing search functionality
within a text editor or data processing application.
#include <string>
#include <iostream>
using namespace std;
int main() {
string sentence = "The quick brown fox jumps over the lazy dog";
cout << "Original sentence: " << sentence << endl;
cout << "Length: " << sentence.length() << endl << endl;
// Find substring
int pos = sentence.find("fox");
if (pos != string::npos) {
cout << "Found 'fox' at position: " << pos << endl;
} else {
cout << "'fox' not found" << endl;
}
// Find character
int charPos = sentence.find('q');
cout << "Found 'q' at position: " << charPos << endl;
// Find last occurrence
int lastPos = sentence.rfind("the");
cout << "Last 'the' found at position: " << lastPos << endl;
// Check if string contains substring
if (sentence.find("dog") != string::npos) {
cout << "Sentence contains 'dog'" << endl;
}
return 0;
}
Output:
Original sentence: The quick brown fox jumps over the lazy dog
Length: 43
Found 'fox' at position: 16
Found 'q' at position: 4
Last 'the' found at position: 31
Sentence contains 'dog'
🔹 String Modification
C++ strings are mutable, allowing in-place modification through methods that alter the content or structure
of the string. Common operations include .append() to add text to the end,
.insert() to add text at a specific position, .replace() to swap out a range of
characters, and .erase() to remove characters. The .substr() function extracts a portion
of the string without modifying the original. These powerful tools are used for tasks like building dynamic SQL
queries, generating HTML/XML, cleaning user input, and implementing text templating systems.
#include <string>
#include <iostream>
using namespace std;
int main() {
string text = "Hello World";
cout << "Original: " << text << endl;
// Substring extraction
string hello = text.substr(0, 5);
string world = text.substr(6, 5);
cout << "First part: " << hello << endl;
cout << "Second part: " << world << endl;
// Replace substring
string replaced = text;
replaced.replace(6, 5, "C++");
cout << "After replace: " << replaced << endl;
// Insert text
string inserted = text;
inserted.insert(5, " Beautiful");
cout << "After insert: " << inserted << endl;
// Erase part of string
string erased = text;
erased.erase(5, 6); // Remove " World"
cout << "After erase: " << erased << endl;
// Append to string
string appended = "Hello";
appended.append(" World!");
cout << "After append: " << appended << endl;
return 0;
}
Output:
Original: Hello World
First part: Hello
Second part: World
After replace: Hello C++
After insert: Hello Beautiful World
After erase: Hello
After append: Hello World!
🔹 String Comparison
String comparison in C++ can be performed using relational operators (==, !=,
<, etc.) or the .compare() member function. The operators provide a clear
syntax for checking equality or lexicographical order (dictionary order), which is crucial for sorting
alphabetically or validating passwords. The .compare() function offers more detailed results, returning
zero for equality or a negative/positive number indicating order. Understanding comparison is vital for implementing
search algorithms, sorting lists of names, managing access control, and organizing data in applications like
phonebooks or file managers.
#include <string>
#include <iostream>
using namespace std;
int main() {
string str1 = "Apple";
string str2 = "Banana";
string str3 = "Apple";
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
cout << "str3: " << str3 << endl << endl;
// Equality comparison
if (str1 == str3) {
cout << "str1 equals str3" << endl;
}
if (str1 != str2) {
cout << "str1 is not equal to str2" << endl;
}
// Lexicographic comparison
if (str1 < str2) {
cout << "str1 comes before str2 alphabetically" << endl;
}
// Using compare() method
int result = str1.compare(str2);
if (result < 0) {
cout << "str1 is less than str2" << endl;
} else if (result > 0) {
cout << "str1 is greater than str2" << endl;
} else {
cout << "str1 equals str2" << endl;
}
return 0;
}
Output:
str1: Apple
str2: Banana
str3: Apple
str1 equals str3
str1 is not equal to str2
str1 comes before str2 alphabetically
str1 is less than str2