# Blogs Hub

### by Sumit Chourasia | May 31, 2020 | Category :coding | Tags : stringalgorithmडेटा-संरचनाc-sharpआसानleetcode

#### Number of Segments in a String - मिनी टीवी

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

Solution:

``````using System;
using System.Collections.Generic;
using System.Text;

{
public class CountSegmentsSoln
{
public int CountSegments(string s)
{
if (s.Length == 0) return 0;
var list = new List<string>();
int count = 1;
if(s[0] == ' ')
{
count = 0;
}

for(int i = 1; i < s.Length-1; i++)
{
if(s[i] == ' ' && s[i+1] != ' ')
{
count++;
}
}

return count;
}
}
}
``````

Time Complexity: O(n)

Space Complexity: O(1)

Unit Tests:

``````using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
[TestClass]
public class CountSegmentsSolnTests
{
[TestMethod]
public void CountSegmentsSoln_First()
{
var s = "Hello, my name is John";
var output = 5;
var res = new CountSegmentsSoln().CountSegments(s);

Assert.AreEqual(res, output);
}

[TestMethod]
public void CountSegmentsSoln_Second()
{
var s = "                ";
var output = 0;
var res = new CountSegmentsSoln().CountSegments(s);

Assert.AreEqual(res, output);
}

[TestMethod]
public void CountSegmentsSoln_Third()
{
var s = "Of all the gin joints in all the towns in all the world,   ";
var output = 13;
var res = new CountSegmentsSoln().CountSegments(s);

Assert.AreEqual(res, output);
}
}
}
``````

Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia