C++ Beginner

cpp_007:Introduction to String Modifiers in C++ , Mastering String Manipulation

codeaddict 2025. 1. 6. 23:00

In C++, the std::string class provides a variety of functions to modify and manipulate strings efficiently. This tutorial is perfect for beginners looking to master string operations such as appending, erasing, inserting, finding, replacing, and more. Let’s dive into these powerful tools with examples and outputs.

1. Appending to a String

The append() function and the + operator allow you to concatenate strings.

Syntax:

  • string.append(str) - Appends the string str to the end of the string.
  • string + str - Concatenates str to the string.

Example 1: Appending Strings

#include <iostream>
using namespace std;

int main() {
    string greeting = "Hello";
    string name = "World";

    // Using append()
    greeting.append(", ").append(name);
    cout << "Greeting with append: " << greeting << endl;

    // Using + operator
    string fullGreeting = greeting + "!";
    cout << "Final Greeting: " << fullGreeting << endl;

    return 0;
}

Output:

Greeting with append: Hello, World
Final Greeting: Hello, World!

2. Erasing Characters or Substrings

The erase() function removes characters from a string.

Syntax:

  • string.erase(index, length) - Removes length characters starting from index.

Example 2: Erasing a Substring

#include <iostream>
using namespace std;

int main() {
    string sentence = "The quick brown fox jumps over the lazy dog.";

    // Removing a substring
    sentence.erase(4, 6);  // Remove "quick " (starting at index 4, length 6)
    cout << "After erase: " << sentence << endl;

    return 0;
}

Output:

After erase: The brown fox jumps over the lazy dog.

3. Inserting into a String

The insert() function adds characters or substrings at a specific index.

Syntax:

  • string.insert(index, str) - Inserts the string str at the specified index.

Example 3: Inserting a Substring

#include <iostream>
using namespace std;

int main() {
    string sentence = "Hello World!";

    // Insert a substring
    sentence.insert(6, "Beautiful ");
    cout << "After insert: " << sentence << endl;

    return 0;
}

Output:

After insert: Hello Beautiful World!

4. Finding and Replacing Substrings

The find() function locates the first occurrence of a substring, while replace() replaces a portion of the string.

Syntax:

  • string.find(str) - Returns the index of the first occurrence of str or string::npos if not found.
  • string.replace(index, length, str) - Replaces length characters starting at index with str.

Example 4: Find and Replace

#include <iostream>
using namespace std;

int main() {
    string sentence = "I love apples.";

    // Finding a substring
    size_t pos = sentence.find("apples");
    if (pos != string::npos) {
        // Replacing the substring
        sentence.replace(pos, 6, "oranges");
    }
    cout << "After replace: " << sentence << endl;

    return 0;
}

Output:

After replace: I love oranges.

5. Extracting Substrings

The substr() function retrieves a portion of the string.

Syntax:

  • string.substr(index, length) - Returns a substring starting at index with length characters.

Example 5: Substring Extraction

#include <iostream>
using namespace std;

int main() {
    string sentence = "The quick brown fox";

    // Extracting a substring
    string word = sentence.substr(10, 5);  // Starting at index 10, length 5
    cout << "Extracted word: " << word << endl;

    return 0;
}

Output:

Extracted word: brown

6. Comparing Strings

The compare() function compares two strings lexicographically.

Syntax:

  • string.compare(str) - Returns:
  • A negative value if the string is less than str.
  • Zero if the string is equal to str.
  • A positive value if the string is greater than str.

Example 6: Comparing Strings

#include <iostream>
using namespace std;

int main() {
    string str1 = "apple";
    string str2 = "banana";

    int result = str1.compare(str2);
    if (result < 0) {
        cout << str1 << " comes before " << str2 << " in lexicographical order." << endl;
    } else if (result > 0) {
        cout << str1 << " comes after " << str2 << " in lexicographical order." << endl;
    } else {
        cout << str1 << " is equal to " << str2 << "." << endl;
    }

    return 0;
}

Output:

apple comes before banana in lexicographical order.

7. Removing the Last Character

The pop_back() function removes the last character of the string.

Syntax:

  • string.pop_back() - Removes the last character of the string.

Example 7: Removing the Last Character

#include <iostream>
using namespace std;

int main() {
    string sentence = "Hello World!";

    // Removing the last character
    sentence.pop_back();
    cout << "After pop_back: " << sentence << endl;

    return 0;
}

Output:

After pop_back: Hello World

Conclusion

By mastering these string modifiers, you can handle any string manipulation task in C++ with confidence. Practice these examples and try combining multiple functions to solve more complex problems.