abhilash poojary
abhilash poojary

Reputation: 127

How to replace all non alpha characters (digits and special characters) from std::string with a space

I am quite new to STL in C++ and am not able to get a proper output even after hours.

int main()
{
    std::string str = "Hello8$World";
    replace(str.begin(), str.end(), ::isdigit, " ");
    replace(str.begin(), str.end(), ::ispunct, " ");
    return 0;
}

I would have been very happy if the above worked but it doesn't.

Upvotes: 2

Views: 6012

Answers (4)

skypjack
skypjack

Reputation: 50548

All in one with a lambda function, more C++14-ish:

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

int main() {
    std::string str = "Hello8$World";

    std::replace_if(str.begin(), str.end(), [](auto ch) {
        return ::isdigit(ch) || ::ispunct(ch);
    }, ' ');

    std::cout << str << std::endl;
    return 0;
}

This way you won't iterate twice over the string.

Upvotes: 5

NathanOliver
NathanOliver

Reputation: 180955

You are using the wrong function. std::replace takes two iterators an old value and a new value. std::replace_if takes two iterators a function and a new value. You also need to use ' ' not " " as the the type the string iterator points to is a char not a string. If you change it to

replace_if(str.begin(),str.end(),::isdigit,' ');
replace_if(str.begin(),str.end(),::ispunct,' ');

It works just fine(Live Example).

Upvotes: 1

LogicStuff
LogicStuff

Reputation: 19617

The name of function that uses a predicate is std::replace_if and you want to replace characters, so ' ', not " " - this is char const*:

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

int main()
{
    std::string str = "Hello8$World";
    std::replace_if(str.begin(), str.end(), ::isdigit, ' ');
    std::replace_if(str.begin(), str.end(), ::ispunct, ' ');
    std::cout << str << std::endl;
    return 0;
}

Upvotes: 1

callyalater
callyalater

Reputation: 3102

You need to use the replace_if function in this case because you are checking a condition. Cppreference has a good explanation of this. The last two parameters of replace_if are the UnaryPredicate (a function that takes one parameter and returns true or false) and the underlying type of object at each location in the iterator (which for strings is a char, not a string).

int main()
{
    std::string str="Hello8$World";
    std::cout << str << std::endl;
    std::replace_if(str.begin(), str.end(), ::isdigit, ' ');
    std::replace_if(str.begin(), str.end(), ::ispunct, ' ');
    std::cout << str << std::endl;
    return 0;
}

Upvotes: 1

Related Questions