How to use regex_iterator to extract and count words from string in C++

1 Answer

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

int main() 
{ 
    const std::string s = "c++ python php java"; 
   
    std::regex words("[^\\s]+"); 
     
    auto words_begin = std::sregex_iterator(s.begin(), s.end(), words); 
    auto words_end = std::sregex_iterator(); 
 
    std::cout << "Total words = " << distance(words_begin, words_end); 
   
    std::cout << std::endl << std::endl << "Words list:" << std::endl; 
    for (std::sregex_iterator si = words_begin; si != words_end; si++) { 
        std::smatch match = *si; 
        std::string word = match.str(); 
        std::cout << word << std::endl; 
    } 
} 

 
/*
run:
 
Total words = 4

Words list:
c++
python
php
java
 
*/

 



answered Feb 8, 2020 by avibootz
edited Aug 21, 2024 by avibootz

Related questions

1 answer 111 views
1 answer 113 views
1 answer 129 views
2 answers 170 views
2 answers 187 views
...