C++ String Functions - Notes & Examples
Commonly Used Functions in C++
length() / size()
string s = "Hello";
cout << s.length(); // 5
cout << s.size(); // 5
empty()
string s = "";
if(s.empty()) cout << "Empty string";
at(pos)
string s = "Hello";
cout << s.at(1); // e
operator[]
string s = "Hello";
cout << s[1]; // e
substr(pos, len)
string s = "HelloWorld";
cout << s.substr(0,5); // Hello
find(str)
string s = "HelloWorld";
cout << s.find("World"); // 5
rfind(str)
string s = "HelloWorldWorld";
cout << s.rfind("World"); // 10
append(str)
string s = "Hello";
s.append("World");
cout << s; // HelloWorld
push_back(ch)
string s = "Hi";
s.push_back('!');
cout << s; // Hi!
insert(pos, str)
string s = "Hello";
s.insert(2, "y");
cout << s; // Heyllo
erase(pos, len)
string s = "Hello";
s.erase(1,2);
cout << s; // Hlo
replace(pos, len, str)
string s = "Hello";
s.replace(0, 2, "Y");
cout << s; // Yllo
compare(str)
string a="abc", b="abd";
cout << a.compare(b); // -1
c_str()
string s = "Hello";
const char* c = s.c_str();
printf("%s", c);
stoi(), stod(), to_string()
string s = "123";
int x = stoi(s); // 123
cout << to_string(45.6); // "45.6"
Mindmap of String Functions
Access■(length, at, []) Modify■(append, insert, erase, replace)
String
Search■(find, rfind, compare) Conversion■(stoi, stod, to_string, c_str)