String Manipulation in C++ | std::string Methods Explained

String Manipulation in C++ | std::string Methods Explained

๐Ÿงต String Manipulation in C++ using std::string

In C++, std::string is a powerful class from the Standard Library that lets you handle and manipulate text data efficiently. Unlike C-style strings, it comes with built-in functions that make operations like concatenation, comparison, and searching easier.

๐Ÿ“˜ Common std::string Methods

  • length() – Returns the number of characters in the string.
  • append() – Adds content to the end of the string.
  • insert() – Inserts characters at a specific index.
  • replace() – Replaces part of the string with another.
  • substr() – Returns a substring from the string.
  • find() – Finds the index of the first occurrence of a substring.
  • erase() – Deletes part of the string.
  • compare() – Compares two strings and returns 0 if equal.
  • c_str() – Returns a C-style string (const char*).

๐Ÿงช Real-world Use Cases

  • Extracting first names from full names using substr()
  • Validating emails using find()
  • Formatting strings in logs or reports
  • Replacing characters in user inputs (e.g., converting spaces to underscores)

๐Ÿ“„ C++ Example: String Manipulation


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

int main() {
    string str = "Welcome";
    
    // Append text
    str.append(" to C++");

    // Insert text
    str.insert(8, "Programming ");

    // Replace text
    str.replace(0, 7, "Hello");

    // Find text
    size_t pos = str.find("C++");

    // Erase part
    str.erase(8, 12); // removes "Programming "

    // Substring
    string sub = str.substr(6, 4);

    // Compare strings
    string other = "Hello to C++";
    int result = str.compare(other);

    // Output results
    cout << "Final string: " << str << endl;
    cout << "Substring (6, 4): " << sub << endl;
    cout << "'C++' found at index: " << pos << endl;
    cout << "Comparison result: " << result << endl;

    return 0;
}
    

๐Ÿ“ Sample Output

Final string: Hello to C++
Substring (6, 4): to C
'C++' found at index: 9
Comparison result: 0

๐Ÿง  Explanation

  • append() adds “ to C++” to the original string.
  • insert() adds “Programming ” at index 8.
  • replace() replaces “Welcome” with “Hello”.
  • erase() deletes 12 characters starting from index 8.
  • find() locates the word “C++” and returns its starting index.
  • compare() returns 0 when the strings match.

These methods provide flexibility for manipulating text in C++ efficiently. Mastering string handling is vital for user input processing, file reading, text formatting, and more in professional C++ development.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences