Let’s Play with C++ String Functions
Strings are more fun when you can twist, cut, measure, or add things to them! 🎉
The string class in C++ comes with many built-in functions that make text handling super easy.
🔧 Example: Basic String Functions
#include <iostream> #include <string> using namespace std; int main() { string msg = "Hello, C++!"; cout << "Length: " << msg.length() << endl; cout << "First letter: " << msg[0] << endl; cout << "Substring: " << msg.substr(7, 3) << endl; msg.append(" You rock!"); cout << "Appended: " << msg << endl; return 0; }
✨ Commonly Used String Functions
length()
– get number of charactersappend(str)
– add more textsubstr(pos, len)
– extract part of the stringat(index)
– get character at a positionfind(str)
– search for a word insidecompare(str)
– compare two stringsempty()
– check if the string is emptyclear()
– erase the content
🔧 Example: Search and Compare
#include <iostream> #include <string> using namespace std; int main() { string a = "coding"; string b = "code"; if (a.compare(b) != 0) { cout << "Strings are different!" << endl; } size_t pos = a.find("ing"); if (pos != string::npos) { cout << "'ing' found at position: " << pos << endl; } return 0; }
💡 Summary
- C++ strings are powerful with lots of handy tools built-in
- You can search, slice, join, and analyze text with ease
- These functions save time and make code cleaner
Now you can slice strings like a ninja! 🥷✂️