22

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?

Terry Li
  • 16,870
  • 30
  • 89
  • 134
  • 5
    Do you use `rank = rank.trim();` or just `rank.trim();`? The second one won't work. – Baz Jul 28 '12 at 11:28
  • provide trim() code that you have used .. – Harmeet Singh Jul 28 '12 at 11:41
  • @TerryLi Maybe you should give us an idea what `(some method)` does. – Baz Jul 28 '12 at 11:44
  • @Baz `(some method)` just tries to extract the ranking for each university from this site:http://www.4icu.org/ca/ – Terry Li Jul 28 '12 at 11:48
  • 2
    Please show a short but complete program demonstrating the problem. You haven't provided enough information at the moment. – Jon Skeet Jul 28 '12 at 11:50
  • You're asking a question about `trim()` which doesn't work. And the code you show doesn't contain any call to the `trim()` method. Show us the relevant code. – JB Nizet Jul 28 '12 at 12:09
  • i dont know why while running your code giving me NPE ... – Harmeet Singh Jul 28 '12 at 12:31
  • @TerryLi: That's still not a short but complete program, is it? – Jon Skeet Jul 28 '12 at 12:35
  • @TerryLi NullpointerException figured out its in row.select("span").first().text().trim() – Harmeet Singh Jul 28 '12 at 12:35
  • @JonSkeet its almost working short code having NPE that i have commented where.. – Harmeet Singh Jul 28 '12 at 12:38
  • @HarmeetSingh The first two rows don't work. I didn't provide complete code. – Terry Li Jul 28 '12 at 12:38
  • @TerryLi you should have provided proper code.. – Harmeet Singh Jul 28 '12 at 12:40
  • @JonSkeet It's not complete enough. I just omitted the code that removes the first two rows from the loop. – Terry Li Jul 28 '12 at 12:40
  • @TerryLi: As you say, it's *not* complete enough. A short but complete program should allow an answerer to copy the code into a text editor, compile it, run it, and see the problem immediately - without the code doing anything unrelated to the problem. As the person asking for help, it's up to you to do enough work to help others help you. Please read http://tinyurl.com/so-hints – Jon Skeet Jul 28 '12 at 12:42

7 Answers7

62

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

Community
  • 1
  • 1
Baz
  • 36,440
  • 11
  • 68
  • 94
  • 3
    @TerryLi See, if you supply sufficient information, we are able to help you. Glad I could help :) – Baz Jul 28 '12 at 12:33
  • Worth noting this answer: http://stackoverflow.com/questions/1437933/how-to-properly-trim-whitespaces-from-a-string-in-java – Quaternion Feb 23 '15 at 09:43
8

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();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

The character is a non-breaking space, and is thus not removed by the trim() method. Iterate through the characters and print the int value of each one, to know which character you must replace by an empty string to get what you want.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

Are you assigning the String?

String rank = " blabla "; 
rank = rank.trim();

Don't forget the second assignment, or your trimmed string will go nowhere.

You can look this sort of stuff up in the API as well: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()

As you can see this method returns a String, like most methods that operate on a String do. They return the modified String and leave the original String in tact.

Julius
  • 2,784
  • 6
  • 32
  • 54
2

I had same problem and did little manipulation on java's trim() method.
You can use this code to trim:

public static String trimAdvanced(String value) {

        Objects.requireNonNull(value);

        int strLength = value.length();
        int len = value.length();
        int st = 0;
        char[] val = value.toCharArray();

        if (strLength == 0) {
            return "";
        }

        while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) {
            st++;
            if (st == strLength) {
                break;
            }
        }
        while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) {
            len--;
            if (len == 0) {
                break;
            }
        }


        return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value;
    }
Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
0

Trim function returns a new copy of the string, with leading and trailing whitespace omitted.

rank = rank.trim();// This will remove and save rank without leading and trailing spaces

will give the result you want.

Replace method will not work if you pass empty string for replacement.

Kishor Sharma
  • 599
  • 8
  • 15
  • 1
    If you are not sure about spaces i will suggest you to use regex to extract the number. Use "((-|\\+)?[0-9]+(\\.[0-9]+)?)+" regex will extract number form string. – Kishor Sharma Jul 28 '12 at 11:49
  • I'll take you advice. But I still wonder what the two spaces denote. – Terry Li Jul 28 '12 at 12:00
  • @TerryLi Unless you give us more information (like a small working program), we will never know... – Baz Jul 28 '12 at 12:02
0

Since String in java are immutable ie they cannot be changed. You need to reassign it to some temporary string. And then using that string you can convert it into int.

String temp=rank.trim()
int te= Integer.parseInt(temp)
heretolearn
  • 6,387
  • 4
  • 30
  • 53