Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String trim has no effect

Tags:

Java String trim is not removing a whitespace character for me.

String rank = (some method); System.out.println("(" + rank + ")"); 

The output is (1 ). Notice the space to the right of the 1.

I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.

The string rank just remains the same either way.

Edit: Full Code::

Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get(); Element table = doc.select("table").get(7); Elements rows = table.select("tr"); for (Element row: rows) {   String rank = row.select("span").first().text().trim();   System.out.println("("+rank+")"); } 

Why can't I remove that space?

like image 761
Terry Li Avatar asked Jul 28 '12 11:07

Terry Li


People also ask

Why trim () is not working?

One space character commonly used in Web pages that TRIM() will not remove is the non-breaking space. If you have imported or copied data from Web pages you may not be able to remove the extra spaces with the TRIM() function if they are created by non-breaking spaces.

Why trim function is not working in Java?

If trim() isn't working (in either Java or TypeScript) then the problem almost certainly isn't with trim(). That thing has proven itself time and time again. The problem is with your string. Specifically, you've likely got whitespace that isn't whitespace.

Does trim () return in Java?

Return Value of trim() in Java The trim() method in Java returns a new string which is the copy of the original string with leading and trailing spaces removed from it.

What does string trim () do in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.


2 Answers

The source code of that website shows the special html character  . Try searching or replacing the following in your java String: \u00A0.

That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails

rank = rank.replaceAll("\u00A0", ""); 

should work. Maybe add a double \\ instead of the \.

like image 97
Baz Avatar answered Sep 24 '22 22:09

Baz


You should assign the result of trim back to the String variable. Otherwise it is not going to work, because strings in Java are immutable.

String orig = "    quick brown fox    "; String trimmed = original.trim(); 
like image 25
Sergey Kalinichenko Avatar answered Sep 26 '22 22:09

Sergey Kalinichenko