C++ String Func

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;
}
  

Try It Now

✨ Commonly Used String Functions

  • length() – get number of characters
  • append(str) – add more text
  • substr(pos, len) – extract part of the string
  • at(index) – get character at a position
  • find(str) – search for a word inside
  • compare(str) – compare two strings
  • empty() – check if the string is empty
  • clear() – 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;
}
  

Try It Now

💡 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! 🥷✂️