nakE
nakE

Reputation: 362

Is there a way I can remove a character from a string?

I want to remove a character ('#') from a string,

I tried to check if the string has '#' with the find function, which it does, then erase this with the erase function.

For some reason I get a run time error that says I have no memory.

Error: std::out_of_range at memory location 0x003BF3B4

#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    std::string str = "Hello World#";

    if (str.find('#')) {
        str.erase('#');
    }

    return 0;
}

The excepted output is: "Hello World"

Upvotes: 0

Views: 497

Answers (3)

Raffallo
Raffallo

Reputation: 694

If you want to delete all '#' from the string:

std::string str = "Hello World#";
std::size_t pos = str.find('#');
while(pos != std::string::npos)
{
    str.erase(pos, 1); //<- edited here
    pos = str.find('#');
}

cout << str;

Upvotes: 0

Soumya Ranjan Swain
Soumya Ranjan Swain

Reputation: 187

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string s = "Hello World#";
    char c = '#';

    /* Removing character c from s */
    s.erase(std::remove(s.begin(), s.end(), c), s.end());
    std::cout << "\nString after removing the character "
              << c << " : " << s;
}

Upvotes: 1

Paolo Mossini
Paolo Mossini

Reputation: 1096

Try something like this:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), '#'), str.end());

Upvotes: 3

Related Questions