How to get the first N words from a string in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
 
std::string FirstNWords(std::string str, int N) {
    std::stringstream iss(str);
     
    std::string word, firstn = "";  
    while (N != 0 && iss >> word) {
        firstn += word + " ";
        N--;
    }
         
    return firstn;        
}
  
  
int main() {
    std::string s = "c++ c c# java python";
    int N = 3;
      
    std::string first3 = FirstNWords(s, N);
     
    std::cout << first3;
      
    return 0;
}
  
  
  
  
  
/*
run:
  
c++ c c#
  
*/

 



answered Feb 8, 2022 by avibootz

Related questions

1 answer 128 views
1 answer 98 views
2 answers 168 views
2 answers 139 views
1 answer 120 views
2 answers 150 views
...