EN
Java - trim whitespace from string
0
points
In this article, we would like to show you how to trim whitespace from string in Java.
Quick solution:
String text = " abc ";
String result = text.trim();
System.out.println(result);
Practical example
In this example, we use String trim()
method to remove whitespaces from the beginning and from the end of the strings.
public class Example {
public static void main(String[] args) throws Exception {
String text1 = " abc";
String text2 = "abc ";
String text3 = " abc ";
String result1 = text1.trim();
String result2 = text2.trim();
String result3 = text3.trim();
System.out.println(result1); // abc
System.out.println(result2); // abc
System.out.println(result3); // abc
}
}
Output:
abc
abc
abc