STRING CLASS IN C++ – DETAILED NOTES WITH EXAMPLES
1. Introduction to std::string
The C++ string class (std::string) is defined in the <string> header and belongs to the std namespace. It
represents a sequence of characters that can grow or shrink dynamically. Unlike C-style character
arrays, std::string automatically manages memory and provides rich member functions for string
manipulation.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Meghna";
cout << "Name: " << name;
return 0;
}
2. Basic Declaration, Initialization, Input and Output
A string object can be declared and initialized in multiple ways:
string s1 = "Hello";
string s2("World");
string empty; // empty string
Input can be taken using operator>> (which stops at space) or getline() (which reads the whole line):
#include <iostream>
#include <string>
using namespace std;
int main() {
string word, line;
cout << "Enter a single word: ";
cin >> word;
[Link](); // clear leftover newline
cout << "Enter a full line: ";
getline(cin, line);
cout << "Word: " << word << "\n";
cout << "Line: " << line << "\n";
return 0;
}
3. length() and size()
Both length() and size() return the number of characters in the string (excluding the null terminator).
They are equivalent for std::string and mainly exist for compatibility with other containers.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
cout << "String: " << s << "\n";
cout << "Length using length(): " << [Link]() << "\n";
cout << "Length using size(): " << [Link]() << "\n";
return 0;
}
4. Accessing Characters: operator[] and at()
Characters in a string can be accessed using the subscript operator [] or the at() member function. The
operator[] does not perform bounds checking, while at() throws an exception if the index is out of range.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << "s[1] = " << s[1] << "\n"; // 'e'
cout << "[Link](4) = " << [Link](4) << "\n"; // 'o'
return 0;
}
5. front() and back()
The front() function returns a reference to the first character, and back() returns a reference to the last
character. These functions are useful when you want to quickly access or modify the ends of the string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "World";
cout << "First character (front): " << [Link]() << "\n";
cout << "Last character (back): " << [Link]() << "\n";
// Modify using front() and back()
[Link]() = 'H';
[Link]() = '!';
cout << "Modified string: " << s << "\n";
return 0;
}
6. Concatenation: operator+ and append()
Strings can be concatenated using the + operator, which creates a new string, or using append(), which
adds text to the existing string object. Concatenation is used when forming messages, building file
paths, etc.
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "Hello";
string b = "World";
string c = a + " " + b; // using +
cout << "Using + : " << c << "\n";
[Link](" ").append(b); // using append()
cout << "Using append(): " << a << "\n";
return 0;
}
7. push_back() and pop_back()
push_back(ch) appends a single character at the end of the string. pop_back() removes the last
character. These are efficient for treating strings like character stacks.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hi";
s.push_back('!'); // s = "Hi!"
cout << "After push_back: " << s << "\n";
s.pop_back(); // s = "Hi"
cout << "After pop_back: " << s << "\n";
return 0;
}
8. insert()
insert(pos, str) inserts the given substring starting at index pos. This is very useful when you need to
insert spaces, punctuation, or additional words into text.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "HelloWorld";
[Link](5, " "); // insert space at index 5
cout << "After insert: " << s << "\n"; // Hello World
return 0;
}
9. erase()
erase(pos, len) removes len characters starting from index pos. It can be used to delete words, extra
spaces, or unwanted characters from a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
[Link](5, 1); // remove 1 character (space)
cout << "After erase: " << s << "\n"; // HelloWorld
return 0;
}
10. replace()
replace(pos, len, new_str) replaces len characters starting at index pos with the contents of new_str. It
is useful for editing phrases, correcting words, or substituting parts of a sentence.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "I love apples";
// replace 'apples' with 'mangoes'
[Link](7, 6, "mangoes"); // start=7, length=6
cout << "After replace: " << s << "\n"; // I love mangoes
return 0;
}
11. find() and rfind()
find() searches for the first occurrence of a character or substring and returns its index. If the target is
not found, it returns string::npos. rfind() works similarly but searches from the end, returning the last
occurrence.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "banana";
size_t pos1 = [Link]('a'); // first 'a'
size_t pos2 = [Link]("ana"); // first 'ana'
size_t pos3 = [Link]('a'); // last 'a'
cout << "First 'a' at index: " << pos1 << "\n";
cout << "First "ana" at index: " << pos2 << "\n";
cout << "Last 'a' at index: " << pos3 << "\n";
return 0;
}
12. substr()
substr(start, length) returns a new string that is a substring of the original, starting at index start and
spanning length characters. It is useful for extracting words, tokens, or specific parts of a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Computer Science";
string word1 = [Link](0, 8); // "Computer"
string word2 = [Link](9, 7); // "Science"
cout << "First word: " << word1 << "\n";
cout << "Second word: " << word2 << "\n";
return 0;
}
13. compare()
compare() compares two strings lexicographically, similar to strcmp() in C. It returns: 0 if both strings
are equal, a negative value if the calling string is less than the argument, and a positive value if it is
greater.
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "Apple";
string b = "Banana";
int result = [Link](b);
if (result == 0)
cout << "Strings are equal\n";
else if (result < 0)
cout << a << " comes before " << b << "\n";
else
cout << a << " comes after " << b << "\n";
return 0;
}
14. clear() and empty()
clear() removes all characters from the string, making it an empty string. empty() checks whether the
string contains no characters and returns true if it is empty. These functions are helpful when resetting
strings or validating input.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << "Before clear, empty() = " << [Link]() << "\n";
[Link]();
cout << "After clear, length = " << [Link]() << "\n";
cout << "After clear, empty() = " << [Link]() << "\n";
return 0;
}
15. Case Conversion (using toupper() and tolower())
Although std::string does not directly provide case-conversion methods, characters can be converted
using the toupper() and tolower() functions from <cctype>. By iterating over the string and applying
these functions, we can convert the entire string to uppercase or lowercase.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s = "HeLLo123";
// convert to uppercase
for (char &c : s) {
c = toupper(c);
}
cout << "Uppercase: " << s << "\n";
// convert to lowercase
for (char &c : s) {
c = tolower(c);
}
cout << "Lowercase: " << s << "\n";
return 0;
}
16. Counting Characters and Substrings
Counting occurrences of a particular character or substring is a common operation in text processing.
Characters can be counted using a simple loop, and substrings can be counted by repeatedly calling
find() and updating the starting position.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "banana";
char ch = 'a';
int countChar = 0;
for (char c : s) {
if (c == ch) countChar++;
}
cout << "Character '" << ch << "' appears " << countChar << " times.\n";
string text = "abababab";
string sub = "ab";
int countSub = 0;
size_t pos = [Link](sub);
while (pos != string::npos) {
countSub++;
pos = [Link](sub, pos + [Link]());
}
cout << "Substring "" << sub << "" appears " << countSub << " times.\n";
return 0;
}
17. Advantages of std::string
1. Automatic memory management – no need to manually handle character arrays or null terminators.
2. Rich set of member functions for insertion, deletion, searching, and replacement. 3. Safer than
C-style strings, helping to avoid buffer overflows. 4. Integrates well with the C++ Standard Library and
algorithms. 5. Easier to write clean, readable code when working with text.