Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
    Please note that the string does not contain any non-printable characters.
    Example: Input: “Hello, my name is John” Output: 5
    Runtime: 4 ms, faster than 9.28% of C++ online submissions for Number of Segments in a String.
    Memory Usage: 4.7 MB, less than 0.65% of C++ online submissions forNumber of Segments in a String.

    1. class Solution {
    2. public:
    3. int countSegments(string s) {
    4. int length = s.length();
    5. int i = 0;
    6. int result = 0;
    7. while(i < length) {
    8. if(!isspace(s[i++])) {
    9. ++result;
    10. while(!isspace(s[i++])){
    11. if (i == length) {
    12. break;
    13. }
    14. };
    15. }
    16. }
    17. return result;
    18. }
    19. };