| Code | What it does |
|---|---|
s.find("x") | position of the first "x", or string::npos if not found |
s.substr(start, count) | a piece of the string: count characters from start |
s.insert(pos, "x") | put "x" in at position pos |
s.erase(pos, count) | remove count characters from pos |
s.replace(pos, count, "x") | swap count characters at pos for "x" |
find
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "I love C++ and I love coding";
cout << text.find("love") << "\n"; // first match
cout << text.find("love", 3) << "\n"; // search again, starting at index 3
if (text.find("Java") == string::npos) {
cout << "No Java here\n";
}
return 0;
}Output
2 17 No Java here
Remember:
string::nposis a special value that means “not found”. Always check for it.
substr: cut out a piece
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "maria@example.com";
int at = email.find('@');
string user = email.substr(0, at); // from 0, 'at' characters
string domain = email.substr(at + 1); // from after @ to the end
cout << "User: " << user << "\n";
cout << "Domain: " << domain << "\n";
return 0;
}Output
User: maria Domain: example.com
insert, erase and replace
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
s.insert(5, ",");
cout << s << "\n";
s.erase(0, 7);
cout << s << "\n";
s.replace(0, 5, "C++");
cout << s << "\n";
return 0;
}Output
Hello, World World C++
Comparing strings
== checks if two strings are equal. < and > compare them in dictionary order (capital letters come before small ones):
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "apple", b = "banana";
cout << boolalpha;
cout << (a < b) << "\n";
cout << (a == "apple") << "\n";
return 0;
}Output
true true