Remove Punctuation from user input Custom function

I have been looking for way to do this but I always end up with the library version to do or its only of a selected string not a getline input string am desperate to know even where to go with this :(
Last edited on
1
2
3
4
5
6
7
8
9
#include <string>
#include <cctype>

std::string remove_punct( const std::string& str )
{
    std::string result ;
    for( char c : str ) if( !std::ispunct(c) ) result += c ;
    return result ;
}

http://coliru.stacked-crooked.com/a/993b07ba953fb42e
OP: and if you want to define your own custom punctuation set:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <algorithm>

std::string remove_punct( const std::string& str );

int main()
{
    std::string test = "\"This is a (some-what) punctuated string!?!.**@#$\"";
    std::cout << remove_punct(test);
}

std::string remove_punct( const std::string& str )
{
    std::string punctuations = {"*@#-$,;!.?\\\"'()"};//edit as required, note escape characters
    std::string result{};

    for (auto itr = str.cbegin(); itr != str.cend(); ++itr)
    {
        if(!std::any_of(punctuations.cbegin(), punctuations.cend(), [itr](char c){return c == *itr;}))
        {
            result += *itr;
        }
    }
    return result;
}

Last edited on
To make it generic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
std::string remove_chars( const std::string& str, const std::string& unwanted )
{
    std::string result ;
    for( char c : str ) if( unwanted.find(c) == std::string::npos ) result += c ;
    return result ;
}

template < typename PREDICATE >
std::string remove_chars_if( const std::string& str, PREDICATE fn )
{
    std::string result ;
    for( char c : str ) if( !fn(c) ) result += c ;
    return result ;
}

http://coliru.stacked-crooked.com/a/8ffa61536a06f494
Topic archived. No new replies allowed.