Trim Spaces from a Line of Text

Solve this Problem
Easy10 min
Topics
Companies
Given a line of text exactly as a user typed it, return it with all spaces at the start and end removed. Spaces between words must stay. When a program reads a whole line of input — nextLine(), input(), getline, fgets — it receives every character typed, including accidental spaces at the edges. TrimmingTrimmingRemoving whitespace from the beginning and end of a string, without touching the inside. that input is usually the first thing to do, so that later comparisons and conversions work on the real content.

Test Case 1:

Input:text = " hello world "
Output:"hello world"
Explanation:Spaces at both ends are removed; the space between the words stays.

Test Case 2:

Input:text = "ready"
Output:"ready"
Explanation:Nothing to trim.

Constraints

  • ◆1 ≤ text.length ≤ 200
  • ◆text contains printable ASCII characters and at least one non-space character

Try the Dry Run

Approach & Solutions

Move Two Indexes InwardGood

Reading a line of input gives you exactly what was typed, stray spaces included. Move a start index right past any leading spaces and an end index left past any trailing spaces, then return the part between them. Spaces in the middle are never touched.

TimeO(n)
SpaceO(n) for the result
class Solution { public String trimText(String text) { int start = 0; int end = text.length() - 1; while (start <= end && text.charAt(start) == ' ') { start++; } while (end >= start && text.charAt(end) == ' ') { end--; } return text.substring(start, end + 1); } }
Built-in TrimOptimal

Every language has a trimming function: strip() in Java and Python, trim() in JavaScript, and find_first_not_of / find_last_not_of in C++. They do the same two-sided scan internally. C has none, so it keeps the two indexes.

TimeO(n)
SpaceO(n) for the result
class Solution { public String trimText(String text) { return text.strip(); } }

Related Problems