PowerShell Script to Count Words in a String
Use
($string -split '\s+').Count in PowerShell to count the number of words in a string by splitting it on spaces.Examples
InputHello
Output1
InputPowerShell is fun
Output3
Input Multiple spaces here
Output3
How to Think About It
To count words, think of splitting the string into parts wherever there is space. Each part is a word. Then count how many parts you have.
Algorithm
1
Get the input string.2
Split the string by spaces to separate words.3
Count the number of parts after splitting.4
Return the count as the number of words.Code
powershell
$string = "PowerShell script to count words" $wordCount = ($string -split '\s+').Count Write-Output $wordCount
Output
5
Dry Run
Let's trace the string 'PowerShell script to count words' through the code
1
Input string
"PowerShell script to count words"
2
Split string by spaces
["PowerShell", "script", "to", "count", "words"]
3
Count words
5
| Word |
|---|
| PowerShell |
| script |
| to |
| count |
| words |
Why This Works
Step 1: Splitting the string
The -split '\s+' operator breaks the string into pieces wherever there is one or more spaces.
Step 2: Counting the pieces
The .Count property counts how many pieces (words) are in the resulting array.
Alternative Approaches
Using Regex Matches
powershell
$string = "Count words using regex" $matches = [regex]::Matches($string, '\w+') Write-Output $matches.Count
This counts word characters and can handle punctuation better but is slightly more complex.
Using .Split() method
powershell
$string = "Split method example" $words = $string.Split(' ', [System.StringSplitOptions]::RemoveEmptyEntries) Write-Output $words.Length
This uses the .NET Split method with option to remove empty entries, useful if string has multiple spaces.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string scans each character once, so time grows linearly with string length.
Space Complexity
The split creates an array of words, so space grows with the number of words.
Which Approach is Fastest?
Using -split is simple and fast for most cases; regex is more flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| -split '\s+' | O(n) | O(n) | Simple word counts with spaces |
| Regex Matches | O(n) | O(n) | Counting words with punctuation |
| .Split() with RemoveEmptyEntries | O(n) | O(n) | Handling multiple spaces explicitly |
Use
-split '\s+' to handle multiple spaces between words easily.Counting words by splitting only on a single space without handling multiple spaces leads to incorrect counts.