Number of Segments in a String - Problem

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Note that the string may contain leading/trailing spaces or multiple spaces between segments.

Input & Output

Example 1 — Basic Case
$ Input: s = "Hello, my name is John"
Output: 5
💡 Note: The five segments are: "Hello,", "my", "name", "is", "John"
Example 2 — Multiple Spaces
$ Input: s = "Hello"
Output: 1
💡 Note: Only one segment: "Hello"
Example 3 — Leading/Trailing Spaces
$ Input: s = " Hello world "
Output: 2
💡 Note: Two segments: "Hello" and "world", ignoring leading/trailing spaces

Constraints

  • 0 ≤ s.length ≤ 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters: ' ', '.', ',', '?', '!', '"', '/', '\', '(', ')'

Visualization

Tap to expand
Number of Segments in a String INPUT String s: H e l l o , _ m y _ n a m e _ i s _ J o h n = Character = Space Segments Found: Hello, my name is John Input String: "Hello, my name is John" ALGORITHM STEPS 1 Split by Space Use split(" ") on string Hello, my name is 2 Filter Empty Remove empty strings Hello, my name is John 3 Count Elements Count non-empty segments [1] [2] [3] [4] [5] 4 Return Count Total segments = 5 s.split(" ").filter(Boolean).length FINAL RESULT Number of Segments: 5 Segments Breakdown: 1 Hello, 2 my 3 name 4 is 5 John Output: 5 Key Insight: The Split and Filter approach leverages built-in string methods to handle multiple spaces automatically. By splitting on spaces and filtering empty strings, we get an array where length equals segment count. TutorialsPoint - Number of Segments in a String | Split and Filter Approach
Asked in
Google 15 Amazon 12
28.5K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen