How to extract all digits from a string in C++

4 Answers

0 votes
#include <iostream>
  
std::string extract_numbers(std::string s) { 
    int len = s.length(); 
    std::string number = ""; 
     
    for (int i = 0; i < len; i++) { 
        if (isdigit(s[i])) 
            number += s[i]; 
    } 
     
    return number;
} 
      
int main() 
{ 
    std::string s = "c++28$c#.net&^java*() php <>/python 3.14.7"; 
    
    std::cout << extract_numbers(s);
} 
    
    
/*
run:
    
283147
    
*/
 

 



answered Aug 13, 2019 by avibootz
edited Sep 16 by avibootz
0 votes
#include <iostream>
#include <string>

std::string extract_digits(const std::string& s) {
    std::string digits;
    
    for (char ch : s) {
        if (std::isdigit(static_cast<unsigned char>(ch))) {
            digits += ch;
        }
    }
    
    return digits;
}

int main() {
    std::string s = "c++28$c#.net&^java*() php <>/python 3.14.7";
    
    std::cout << extract_digits(s) << std::endl;   
}

   
/*
run:
   
283147
   
*/

 



answered Sep 16 by avibootz
0 votes
#include <iostream>
#include <string>
#include <algorithm>

std::string extract_digits_copy_if(const std::string& s) {
    std::string digits;
    
    std::copy_if(s.begin(), s.end(), std::back_inserter(digits),
                 [](char ch){ return std::isdigit(static_cast<unsigned char>(ch)); });
    
    return digits;
}

int main() {
    std::string s = "c++28$c#.net&^java*() php <>/python 3.14.7";
    std::cout << extract_digits_copy_if(s) << std::endl;   // "283147"
}

    
    
/*
run:
    
283147
    
*/
 

 



answered Sep 16 by avibootz
0 votes
#include <iostream>
#include <string>
#include <regex>

std::string extract_digits_regex(const std::string& s) {
    std::regex re("\\d+");
    std::smatch match;
    std::string result;

    std::string temp = s;
    while (std::regex_search(temp, match, re)) {
        result += match.str();
        temp = match.suffix();
    }
    
    return result;
}

int main() {
    std::string s = "c++28$c#.net&^java*() php <>/python 3.14.7";
    
    std::cout << extract_digits_regex(s) << std::endl;
}


    
    
/*
run:
    
283147
    
*/
 

 



answered Sep 16 by avibootz
...