Normalize Whitespace

Easy~10 min

Given a string s, normalize its whitespace by:

  1. Trimming leading and trailing whitespace
  2. Replacing all consecutive internal whitespace characters (spaces, tabs, newlines) with a single space

For example, " hello world " becomes "hello world".

Examples

Example 1
Input: s = " hello world "
Output: "hello world"
Explanation: Leading/trailing spaces removed, internal spaces collapsed to one.
Example 2
Input: s = "foo bar baz"
Output: "foo bar baz"
Explanation: Multiple internal spaces between words are collapsed to single spaces.
Example 3
Input: s = " "
Output: ""
Explanation: A string of only whitespace becomes an empty string after trimming.

Constraints

  • 0 <= s.length <= 10^4
  • s consists of printable ASCII characters including spaces, tabs, and newlines.
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run