C++ String Functions - Notes & Examples
Commonly Used Functions in C++
length() / size()
string s = "Hello";
cout << [Link](); // 5
cout << [Link](); // 5
empty()
string s = "";
if([Link]()) cout << "Empty string";
at(pos)
string s = "Hello";
cout << [Link](1); // e
operator[]
string s = "Hello";
cout << s[1]; // e
substr(pos, len)
string s = "HelloWorld";
cout << [Link](0,5); // Hello
find(str)
string s = "HelloWorld";
cout << [Link]("World"); // 5
rfind(str)
string s = "HelloWorldWorld";
cout << [Link]("World"); // 10
append(str)
string s = "Hello";
[Link]("World");
cout << s; // HelloWorld
push_back(ch)
string s = "Hi";
s.push_back('!');
cout << s; // Hi!
insert(pos, str)
string s = "Hello";
[Link](2, "y");
cout << s; // Heyllo
erase(pos, len)
string s = "Hello";
[Link](1,2);
cout << s; // Hlo
replace(pos, len, str)
string s = "Hello";
[Link](0, 2, "Y");
cout << s; // Yllo
compare(str)
string a="abc", b="abd";
cout << [Link](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)