In this post we’ll see what all options are there in Java String class to remove leading, trailing spaces from a String, even spaces from in between the words in a String.
String class methods for removing spaces
- trim()- Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020'
- strip()- Java 11 onward there is also a strip() method which does the same task of removing all leading and trailing white spaces. How it differs from trim() is that in strip() method whether the specified character is white space or not is determined by internally using Character.isWhitespace() method which also considers unicodes like \u2007, \u202F as whitespaces (greater than 'U+0020')
- stripLeading()- Variant of strip() method that removes all leading white spaces.
- stripTrailing()- Variant of strip() method that removes all trailing white spaces.
- replaceAll()- To remove spaces any where in a string; leading, trailing or between words replaceAll() method can be used with regular expression “\\s+” as parameter to match any numbers of spaces anywhere.
Removing spaces from Java string examples
Let us see examples using the methods mentioned above.
1. Using trim()
method to remove spaces from a String in Java. This method removes leading and trailing spaces not the spaces between words.
public class StringSpaceRemoval { public static void main(String[] args) { String str = " Example String "; str = str.trim(); System.out.println("String- " + str); } }
Output
String- Example String
2. Using strip()
method to remove spaces. This method is added in Java 11 and it takes into account unicodes categorized as space separator having value greater than '\u0020
public class StringSpaceRemoval { public static void main(String[] args) { String str = '\u2001'+"Example String"; System.out.println("String- " + str); System.out.println("String after trim- " + str.trim()); str = str.strip(); System.out.println("String after strip- " + str); } }
Output
String- Example String String after trim- Example String String after strip- Example String
As you can see trim() method is not able to remove space created by ‘\u2001’ but strip() method could.
3. If you have to remove all the spaces; leading, trailing and spaces between the words then you can use replaceAll()
method.
public class StringSpaceRemoval { public static void main(String[] args) { String str = " Example String "; // regex to match any number of spaces str = str.replaceAll("\\s+", ""); System.out.println(str); } }
Output
ExampleString
That's all for this topic Java trim(), strip() - Removing Spaces From String. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Basics Tutorial Page
Related topics
You may also like-
No comments:
Post a Comment