Number of Segments in a String in C++


Suppose we have a string s. We have to count the number of segments in a string, where a segment is defined to be a contiguous sequence of characters (no whitespace).

So, if the input is like "Hello, I love programming", then the output will be 4, as there are 4 segments.

To solve this, we will follow these steps −

  • n := 0

  • for initialize i := 0, when i < size of s, update (increase i by 1), do −

    • if s[i] is not equal to white space, then −

      • (increase n by 1)

    • while (i < size of s and s[i] is not equal to white space), do −

      • (increase i by 1)

  • return n

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int countSegments(string s) {
      int n = 0;
      for(int i = 0; i < s.size(); i++){
         if(s[i] != ' ')
            n++;
         while( i < s.size() && s[i] != ' ')
            i++;
      }
      return n;
   }
};
main(){
   Solution ob;
   cout << (ob.countSegments("Hello, I love programming"));
}

Input

"Hello, I love programming"

Output

4

Updated on: 10-Jun-2020

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements