# Number of Segments in a String
**Difficulty:** EASY
[External](https://leetcode.com/problems/number-of-segments-in-a-string)
Canonical: https://scaleengineer.com/dsa/problems/number-of-segments-in-a-string
**Data structures:** 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**.

**Example 1:**

**Input:** s = "Hello, my name is John"
**Output:** 5
**Explanation:** The five segments are ["Hello,", "my", "name", "is", "John"]

**Example 2:**

**Input:** s = "Hello"
**Output:** 1

**Constraints:**

* `0 <= s.length <= 300`
* `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.:"`.
* The only space character in `s` is `' '`.

# Approaches
## Using Built-in Split Function
This approach leverages the built-in `split` function available in Java's `String` class. The idea is to split the string by spaces and then count the number of resulting non-empty parts. It's a very direct and readable solution.
**Time:** O(N), where N is the length of the string. The `trim()` and `split()` operations both require iterating through the string. · **Space:** O(N), where N is the length of the string. The `split()` method creates a new array of strings, and the total size of these strings can be proportional to the original string's length in the worst case (e.g., 'a b c d ...').
**Pros:** Very concise and easy to read and write.; Leverages well-tested standard library functions.
**Cons:** Inefficient in terms of space, as it creates an intermediate array of strings.; The overhead of regular expression processing can make it slightly slower than a manual scan for simple cases.
### Explanation
The core of this method is to first prepare the string and then use the `split` function.

1.  **Trim the String**: The input string `s` is first trimmed using `s.trim()` to remove any leading or trailing whitespace. This is crucial to handle cases like `"   hello world   "`, which should result in 2 segments, not more due to leading/trailing spaces.
2.  **Handle Empty String**: If the trimmed string is empty, it means the original string was either empty or contained only spaces. In this case, there are no segments, so we return 0.
3.  **Split the String**: The trimmed string is then split using a regular expression that matches one or more whitespace characters (`"\\s+"`). This correctly handles multiple spaces between words.
4.  **Return Length**: The number of segments is simply the length of the array returned by the `split` method.

```java
class Solution {
    public int countSegments(String s) {
        // Trim leading and trailing spaces
        String trimmed = s.trim();
        
        // If the string is empty after trimming, there are no segments
        if (trimmed.isEmpty()) {
            return 0;
        }
        
        // Split the string by one or more spaces
        String[] segments = trimmed.split("\\s+");
        
        // The number of segments is the length of the resulting array
        return segments.length;
    }
}
```
### Algorithm
- Trim the leading and trailing whitespace from the input string `s`.
- Check if the resulting string is empty. If it is, return 0.
- Split the trimmed string by the regex `\s+` which matches one or more space characters.
- Return the length of the resulting array of strings.

## In-place Counting with a Single Pass
This approach iterates through the string character by character, counting segments without allocating extra space for substrings. It is the most efficient solution in terms of memory usage.
**Time:** O(N), where N is the length of the string. We perform a single pass through the string. · **Space:** O(1). We only use a constant amount of extra space for the counter and loop variable, regardless of the input string size.
**Pros:** Highly efficient in terms of space (O(1) space complexity).; Generally faster than the split-based approach due to no overhead from creating new objects or using regex.
**Cons:** The logic is slightly more complex to write and understand compared to the one-liner `split` method.
### Explanation
Instead of splitting the string into an array, we can count the segments by identifying their starting points. A segment starts at a non-space character that is either at the beginning of the string or is preceded by a space.

We can implement this with a single loop and a counter.

1.  **Initialize Counter**: A variable `count` is initialized to 0.
2.  **Iterate Through String**: We loop through the string from the first character (`i = 0`) to the last.
3.  **Identify Segment Start**: Inside the loop, for each character `s.charAt(i)`, we check two conditions:
    - The current character is not a space (`s.charAt(i) != ' '`).
    - It is the start of a new segment. This is true if it's the very first character of the string (`i == 0`) OR the character before it was a space (`s.charAt(i - 1) == ' '`).
4.  **Increment Counter**: If both conditions are met, we've found the beginning of a new segment, so we increment `count`.
5.  **Return Count**: After the loop finishes, `count` holds the total number of segments.

```java
class Solution {
    public int countSegments(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            // A segment starts at a non-space character that is
            // either at the beginning of the string or preceded by a space.
            if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                count++;
            }
        }
        return count;
    }
}
```
### Algorithm
- Initialize a segment counter `count` to 0.
- Iterate through the string `s` with an index `i` from 0 to `s.length() - 1`.
- For each character `s.charAt(i)`, check if it is a non-space character.
- If it is a non-space character, check if it's the start of a segment. This is true if `i` is 0 or the previous character `s.charAt(i-1)` was a space.
- If both conditions are met, increment the `count`.
- After the loop, return the final `count`.

# Solutions
### Java

```java
class Solution {
public
  int countSegments(String s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
        ++ans;
      }
    }
    return ans;
  }
}

```

### CPP

```cpp
class Solution {
public:
  int countSegments(string s) {
    int ans = 0;
    for (int i = 0; i < s.size(); ++i) {
      if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
        ++ans;
      }
    }
    return ans;
  }
};

```

### Python

```python
class Solution:
    def countSegments(self, s: str) -> int: ans = 0 for i, c in enumerate(s): if c != ' ' and (i == 0 or s[i - 1] == ' '): ans += 1 return ans

```
