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:
xxxxxxxxxx
1
String text = " abc ";
2
3
String result = text.trim();
4
5
System.out.println(result);
In this example, we use String trim()
method to remove whitespaces from the beginning and from the end of the strings.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) throws Exception {
4
String text1 = " abc";
5
String text2 = "abc ";
6
String text3 = " abc ";
7
8
String result1 = text1.trim();
9
String result2 = text2.trim();
10
String result3 = text3.trim();
11
12
System.out.println(result1); // abc
13
System.out.println(result2); // abc
14
System.out.println(result3); // abc
15
}
16
}
Output:
xxxxxxxxxx
1
abc
2
abc
3
abc