How to strip all non-numeric characters from string in C++

2 Answers

0 votes
#include <iostream>
#include <regex>

using namespace std;

int main() {
    string s = "2a1-0/R@a9f#4K$$cC3K^htPam8vlQWhJ";

    s = std::regex_replace(s, std::regex(R"([\D])"), "");
    
    std::cout << s;
}



/*
run:

2109438

*/

 



answered Jun 15, 2020 by avibootz
0 votes
#include <iostream>
#include <algorithm>

using namespace std;

bool not_a_digit(char ch) {
    return '0' <= ch && ch <= '9';
}

std::string remove_non_numeric(const std::string &s) {
    string result;
    copy_if(s.begin(), s.end(), std::back_inserter(result), not_a_digit);
    
    return result;
}

int main() {
    string s = "2a1-0/R@a9f#4K$$cC3K^htPam8vlQWhJ";

    s = remove_non_numeric(s);
    
    std::cout << s;
}



/*
run:

2109438

*/

 



answered Jun 15, 2020 by avibootz
edited Jun 15, 2020 by avibootz

Related questions

2 answers 155 views
1 answer 136 views
2 answers 208 views
2 answers 277 views
2 answers 266 views
1 answer 180 views
...