C++ String Erase šŸŽÆ

beginner
8 min

C++ String Erase šŸŽÆ

Welcome to this comprehensive guide on C++ String Erase! In this lesson, we'll delve into the world of C++ strings, learn how to manipulate them, and specifically focus on how to remove characters from strings. Let's get started!

Introduction šŸ“

Before we dive into the erase() function, let's first understand what strings are in C++ and why we might need to remove characters from them.

A string in C++ is an array of characters with one extra benefit - it automatically manages its size. This means we can work with strings as if they were ordinary arrays, but we don't have to worry about allocating and deallocating memory.

Now, there are times when we may want to remove a specific character or a range of characters from a string, and that's where the erase() function comes into play.

The erase() Function šŸ’”

The erase() function in C++ allows us to remove a specific character or a range of characters from a string. It modifies the original string and returns a reference to the string so we can chain multiple operations.

Here's the function's syntax:

cpp
string& erase( size_t pos, size_t len = npos );
  • pos: The position at which the removal starts.
  • len: The number of characters to be removed. If len is not provided, all characters starting from pos will be removed until the end of the string.

Example 1: Removing a Single Character āœ…

Let's consider an example where we remove the third character ('c') from the string "HelloWorld".

cpp
#include <iostream> #include <string> int main() { std::string myString = "HelloWorld"; myString.erase(2, 1); // Remove the third character (c) std::cout << myString << std::endl; // Output: HelloWorld return 0; }

Example 2: Removing a Range of Characters āœ…

Now, let's see how we can remove a range of characters. We'll remove the characters from position 4 (inclusive) to position 7 (exclusive) from the string "HelloWorld123".

cpp
#include <iostream> #include <string> int main() { std::string myString = "HelloWorld123"; myString.erase(3, 4); // Remove characters from position 4 to 7 (inclusive) std::cout << myString << std::endl; // Output: Hello13 return 0; }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

Given a string "AppleBananaOrange", if we want to remove the substring "Apple", what position should we start from and how many characters should we remove?

That's it for our C++ String Erase lesson! We've covered the basics of the erase() function, seen examples of removing a single character and a range of characters, and even had a fun quiz. As you practice more, you'll become more confident with manipulating strings in C++. Happy coding! šŸš€