Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim leading or trailing characters from a string?

Tags:

java

string

trim

How can I trim the leading or trailing characters from a string in java?

For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.

like image 677
Brad Parks Avatar asked Sep 05 '14 17:09

Brad Parks


People also ask

How do you cut leading and trailing spaces from a string?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I remove a trailing character from a string?

Use the Python string rstrip(chars) method to return a copy of a string with the trailing characters removed. Use the rstrip() method without argument to return a copy of a string with the trailing whitespace removed.

How do you remove leading and trailing characters from a string in Java?

In the StringUtils class, we have the methods stripStart() and stripEnd(). They remove leading and trailing characters respectively.

What are leading and trailing characters?

L'string' - a leading string to appear at the beginning of the character or numeric data column. T'string' - a trailing string to appear at the end of the character or numeric data column.


2 Answers

You could use

Leading:

System.out.println("//test/me".replaceAll("^/+", "")); 

Trailing:

System.out.println("//test/me//".replaceAll("/+$", "")); 
like image 140
Reimeus Avatar answered Sep 22 '22 21:09

Reimeus


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

For example:

System.out.println(StringUtils.stripStart("//test/me", "/")); 

will output:

test/me

Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:

like image 25
Brad Parks Avatar answered Sep 19 '22 21:09

Brad Parks