Library contents

Java String.trim

Remove leading and trailing characters whose value is at most U+0020.

A simple example

String.trim

  1. Start with " A "
  2. Do this Remove surrounding spaces
  3. Result "A"
The middle letter stays in place while both ends lose their spaces.

Syntax

Java syntax
public String trim()
JDK 21 method signatures (1)
public String trim()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Clean padding from a classroom code

A user pastes a name or code from another application. Remove the unwanted outer padding while preserving the spaces and letters that belong to the actual value.

From the programString code = " CS 101 "
ResultCS 101
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String code = "  CS 101  ";
        System.out.println(code.trim());
    }
}
Output
CS 101

The space between the subject and number is retained.

Advertisements

Check the boundary of legacy trimming

An older import includes padding around a fixed-width label. Compare the characters actually removed by the chosen trimming operation, since a visible margin can contain more than an ordinary space.

From the programString label = "\u2003tea\u2003"
Result5
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String label = "\u2003tea\u2003";
        System.out.println(label.trim().length());
    }
}
Output
5

An em space is above U+0020, so neither end is removed.

Clean a course import

A course name arrives padded on both sides. Remove leading and trailing ASCII spaces before placing the text between the display brackets.

Given' Art '
Worked result[Art]

What to watch for

Use strip for Java whitespace beyond the older trim range. Interior spaces are preserved.

Documentation for String.trim