Java String trim has no effect

Terry Li picture Terry Li · Jul 28, 2012 · Viewed 34.4k times · Source

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?

Answer

Baz picture Baz · Jul 28, 2012

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 \.