Skip to content

Word Count

Problem Description

Given a string A. The string contains some words separated by spaces.

Return the number of words in the given string.

Problem Constraints

1 <= |A| <= 10^5
Ai = { lowercase English letters or spaces}
1 <= |A| <= 10^5
Ai = { lowercase English letters or spaces}

Input Format

The first and only argument is a string A.
The first and only argument is a string A.

Output Format

Return an integer.
Return an integer.

Example Input

Input 1:
A = "bonjour"

Input 2:
A = "hasta la vista"
Input 1:
A = "bonjour"

Input 2:
A = "hasta la vista"

Example Output

Output 1:
1

Output 2:
3
Output 1:
1

Output 2:
3

Example Explanation

Explanation 1:
The string has only one word "bonjour".

Explanation 2:
The string have three words "hasta", "la", "vista".
Explanation 1:
The string has only one word "bonjour".

Explanation 2:
The string have three words "hasta", "la", "vista".

Solution

swift
import Foundation

class Solution {
	func solve(_ A: inout String) -> Int {
        var count = 0
        
        return A.components(separatedBy:" ").filter{$0.count > 0}.count
        
        // for str in A.components(separatedBy:" ") {
        //     if !str.isEmpty {
        //         count += 1
        //     }
        //     // count += 1
        // }
        // return count
	}
}
import Foundation

class Solution {
	func solve(_ A: inout String) -> Int {
        var count = 0
        
        return A.components(separatedBy:" ").filter{$0.count > 0}.count
        
        // for str in A.components(separatedBy:" ") {
        //     if !str.isEmpty {
        //         count += 1
        //     }
        //     // count += 1
        // }
        // return count
	}
}

References