In Java, you can remove leading and trailing whitespace from a string using strip() (Java 11+) or trim():
s.strip() // removes leading and trailing whitespace (Unicode-aware)
s.trim() // removes leading and trailing ASCII whitespace
s.stripLeading() // removes only leading whitespace
s.stripTrailing()// removes only trailing whitespace
Here are some examples:
String s = " hello ";
System.out.println(s.strip()); // "hello"
System.out.println(s.stripLeading()); // "hello "
System.out.println(s.stripTrailing()); // " hello"
These methods return a new String — the original is not modified.
Assignment
Follow the Coding Tutorial and strip whitespace from s!
Hint
Use s.strip() and assign the result to result.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
