Topic 24 of 83
String Functions
Overview
String manipulation is tested heavily in interviews (e.g., checking palindromes, finding substrings). The `<string>` library provides robust built-in functions.
Syntax
cpp
#include <string>
using namespace std;
string s = "Hello World";
int len = s.length(); // 11
string sub = s.substr(0, 5); // "Hello" (start, length)
int pos = s.find("World"); // 6 (returns string::npos if not found)
s.replace(6, 5, "C++"); // "Hello C++"
s.erase(5, 4); // removes charactersCommon Pitfalls
- Assuming `find()` returns `-1` on failure. It returns `string::npos`, which is a massive unsigned integer.
Interview Tips
- When using `find()`, always check the return value against `std::string::npos` to see if the substring was actually found.
- Be comfortable using `substr` and `find` to parse sentences into words.
Real-World Example
Extracting a file extension from a filename.
example
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string filename = "report.2023.pdf";
// Find the LAST dot
size_t dotPos = filename.rfind(".");
if (dotPos != string::npos) {
string ext = filename.substr(dotPos + 1);
cout << "Extension: " << ext << endl;
}
return 0;
}