How to count spaces in a string with C++

1 Answer

0 votes
#include <iostream>
 
int countSpaces(std::string s) {
    int spaces = 0;
    
    for (int i = 0; s[i]; i++) {
        if (std::isspace(s[i])) {
            spaces++;
        }
    }
    
    return spaces;
}
   
int main(void) {
    std::string s = "C++   is a general-purpose programming language";
           
    std::cout << countSpaces(s);
    
    return 0;
}
   
   
   
   
/*
run:
     
7
     
*/

 



answered Feb 16, 2022 by avibootz

Related questions

1 answer 134 views
134 views asked Jun 8, 2018 by avibootz
2 answers 107 views
1 answer 99 views
99 views asked Feb 16, 2022 by avibootz
...