Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim characters in Java

Tags:

java

string

trim

How can I trim characters in Java?
e.g.

String j = “\joe\jill\”.Trim(new char[] {“\”}); 

j should be

"joe\jill"

String j = “jack\joe\jill\”.Trim("jack"); 

j should be

"\joe\jill\"

etc

like image 261
Quintin Par Avatar asked Jan 18 '10 17:01

Quintin Par


People also ask

How do you trim a character in Java?

Java String trim()The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.

What does the trim () do in Java?

trim() in Java removes all the leading and trailing spaces in the string. It does not take any parameter and returns a new string. The trim method checks for the Unicode value of the space and eliminates it. The trim() in Java does not remove middle spaces.

How do you trim leading characters in Java?

You can use Apache StringUtils. stripStart to trim leading characters, or StringUtils. stripEnd to trim trailing characters.

What trim () in string does?

Trim() Removes all leading and trailing white-space characters from the current string.


2 Answers

Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils there is a strip(String, String) method that will do what you want.

I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.

like image 94
Colin Gislason Avatar answered Oct 07 '22 20:10

Colin Gislason


This does what you want:

public static void main (String[] args) {     String a = "\\joe\\jill\\";     String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");     System.out.println(b); } 

The $ is used to remove the sequence in the end of string. The ^ is used to remove in the beggining.

As an alternative, you can use the syntax:

String b = a.replaceAll("\\\\$|^\\\\", ""); 

The | means "or".

In case you want to trim other chars, just adapt the regex:

String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining 
like image 31
Paulo Guedes Avatar answered Oct 07 '22 19:10

Paulo Guedes