C++ String Functions

C++ provides a wide range of string functions through the std::string class to manipulate and process text easily. These functions help in measuring, modifying, searching, and comparing strings.

Commonly Used String Functions

  • length() / size() – Returns the number of characters in the string.
  • empty() – Checks if the string is empty. Returns true if empty.
  • append() – Adds another string to the end.
  • insert() – Inserts a string at a specific position.
  • erase() – Deletes characters from the string.
  • replace() – Replaces a portion of the string with another string.
  • substr() – Returns a substring starting from a given index.
  • find() – Searches for a substring and returns its position.
  • c_str() – Converts the string to a C-style string (const char*).

Example Program: String Functions

#include <iostream>
#include <string>
using namespace std;

int main() {

    string text = "Hello, C++ World!";

    // length()
    cout << "Length: " << text.length() << endl;

    // empty()
    cout << "Is empty? " << (text.empty() ? "Yes" : "No") << endl;

    // append()
    text.append(" Welcome!");
    cout << "After append: " << text << endl;

    // substr()
    cout << "Substring: " << text.substr(7, 5) << endl;

    // find()
    cout << "Position of 'C++': " << text.find("C++") << endl;

    // replace()
    text.replace(7, 5, "Java");
    cout << "After replace: " << text << endl;

    return 0;
}

Output

Length: 17
Is empty? No
After append: Hello, C++ World! Welcome!
Substring: C++ W
Position of 'C++': 7
After replace: Hello, Java World! Welcome!

Important Notes

  • std::string provides a large number of built-in functions for efficient text manipulation.
  • Most string functions return values or modify the original string directly.
  • Always check string indices carefully to avoid out-of-range errors when using functions like substr(), replace(), or erase().

Next Topic

Next, learn about C++ Pointers.