English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java String trim() method returns a string with any leading (beginning) and trailing (ending) spaces removed.
The syntax of the string trim() method is:
string.trim()
trim() method without any parameters
Returns a string with leading and trailing spaces removed
If there are no spaces at the beginning or end, the original string is returned.
Note:In programming, whitespace is any character or series of characters that represent horizontal or vertical space. For example: space, newline \n, tab \t, vertical tab \v, etc.
class Main { public static void main(String[] args) { String str1 = "\t\t\tLearn\t\tJava\tProgramming"; String str2 = "Learn\nJava Programming\n\n\t"; System.out.println(str1.trim()); System.out.println(str2.trim()); } }
Output Result
Learn Java Programming Learn Java Programming
Here, str1.trim() returns
"Learn\t\tJava\tProgramming"
Similarly, str2.trim() returns
"Learn\nJava\n\n\tProgramming"
From the above example, it can be seen that the trim() method only removes leading and trailing spaces. It does not remove spaces appearing in the middle.
If necessaryAll whitespace characters from the stringThen you can removeString replaceAll() methodUsing appropriate regular expressions.
class Main { public static void main(String[] args) { String str1 = "Learn\nJava\n\n\t"; String result; //Replace all whitespace characters with an empty string result = str1.replaceAll("\\s", ""); System.out.println(result); // LearnJava } }