Count Words in String with Special Characters
Filed under BNY Mellon
Free read 2 of 3Define exactly which punctuation marks are considered valid tokens and how adjacent symbols should be segmented.
The question
Count the number of valid words in a text string where specified punctuation marks are treated as valid word tokens.
Constraints
- String length is between 1 and 10^4.
- May contain alphanumeric characters, spaces, and special punctuation tokens.
- Case insensitive or sensitive as specified by problem rules.
Examples
- Input
- text = "Hello, world! How's it going?"
- Output
- 6
- Why
- Splitting by whitespace and accounting for tokens yields 6 valid words.
Approach
Define exactly which punctuation marks are considered valid tokens and how adjacent symbols should be segmented.
Iterate character by character, maintaining state to manually extract words and punctuation tokens.
Use regex or string split functions with custom delimiters to parse tokens in a single pass efficiently.
Empty string, string with only spaces, and hyphenated words.
Tips
- What they are testing: Test with leading/trailing spaces, multiple consecutive spaces, and strings consisting entirely of punctuation.
- Common mistake: Failing to handle edge cases like empty strings or strings with only special characters.
Related BNY Mellon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.