The Number of Segments in a String solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Number of Segments in a String
C++, Python and TypeScript solutions for Number of Segments in a String.
Solution files
Python•number-of-segments-in-a-string/synced-solution.py
def countSegments(s):
return len(s.split())
C++•number-of-segments-in-a-string/synced-solution.cpp
class Solution {
public:
int countSegments(string s) {
int count = 0;
int i = 0;
int n = s.length();
while (i < n) {
while (i < n && s[i] == ' ') {
i++;
}
if (i < n) {
count++;
while (i < n && s[i] != ' ') {
i++;
}
}
}
return count;
}
};
TypeScript•number-of-segments-in-a-string/synced-solution.ts
function countSegments(s: string): number {
return s.split(/\s+/).filter(segment => segment.length > 0).length;
}