20

I am trying to trim leading whitespaces from the string and I do not know what is wrong with my approach, any suggestions would be appreciated ?

Code:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

am reading poNumber from csv file as "     IG078565 and IG083060 " and output also am getting same value with same whitespaces, not sure why ?

Updated

Adding complete method for better context:

public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }

Thanks.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Rachel
  • 100,387
  • 116
  • 269
  • 365
  • 1
    What are you expecting the code to do and what does it do instead? – Michael Borgwardt Jan 18 '11 at 20:24
  • String#trim() returns the original string if it's given an empty string, so I'm not sure that ternary conditional is even necessary... Someone want to tell me if I'm wrong? – Platinum Azure Jan 18 '11 at 20:25
  • @Michael: Code should check if the value is Null then insert as it is in db and if it is not null then it should remove leading and trailing spaces and then insert. – Rachel Jan 18 '11 at 20:25
  • 1
    I notice you are using `this.poNumber` on the left hand side of the assignment and just `poNumber` on the right hand side. Is there both an instance variable and a local variable called `poNumber`? – mikej Jan 18 '11 at 20:25
  • Yes. I have both instance and local variable. – Rachel Jan 18 '11 at 20:26
  • 1
    @Rachel: You can't expect `poNumber` to be trimmed after, only `this.poNumber`. With which are you experiencing the error? – Mark Peters Jan 18 '11 at 20:27
  • possible duplicate of [How to properly trim whitespaces from a string in Java?](http://stackoverflow.com/questions/1437933/how-to-properly-trim-whitespaces-from-a-string-in-java) – Matt Ball Mar 21 '13 at 22:37

4 Answers4

48

Update It appears your whitespace is not a whitespace (ascii=32). Yours is with code 160, which is a no-breaking space. trim() does not handle it. So you must do something like this:

this.poNumber = poNumber.replace(String.valueOf((char) 160), " ").trim();

You'd better create an utility - YourStringUtils.trim(string) and there perform the two operations - both .trim() and the replace(..)


Original answer:

Just use this.poNumber = poNumber.trim();

If there is a possibility for poNumber to be null, then you can use the null-safe this.poNumber = StringUtils.trim(poNumber); from commons-lang.

You can also use trimToEmpty(..) from the same class, if you want null to be transformed to an empty string.

If you don't want to rely on commons-lang, then just add an if-clause:

if (poNumber != null) {
    this.poNumber = poNumber.trim();
}

As noted in the comments under the question - make sure you are checking the right variable after the trimming. You should check the instance variable. Your parameter (or local variable, I can't tell) does not change, because strings are immutable.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    @Rachel - I added an update about `null`. And your code will also give null – Bozho Jan 18 '11 at 20:27
  • @Rachel Your original code would give the same error. You might be confusing java with some other language. – Nikita Rybak Jan 18 '11 at 20:27
  • I did used `StringUtils.trim(poNumber)` and am getting values as poNumber:     IG078565 and IG083060, which still has spaces. – Rachel Jan 18 '11 at 20:31
  • @Rachel see my last paragraph – Bozho Jan 18 '11 at 20:32
  • I don't see why it should be null and not "". That depends on how the CSV is parsed. But anyway, if null would be a problem, use this.poNumber = poNumber==null ? "" : poNumber.trim() (or whichever value you prefer to assign to poNumber for null entries). – Axel Jan 18 '11 at 20:32
  • In my sysout am printing value of this.poNumber and it is printing me value with whitespaces – Rachel Jan 18 '11 at 20:42
  • @Rachel - how about showing the whole code of the method in question? – Bozho Jan 18 '11 at 20:42
  • Even this one is not removing the whitespaces: `System.out.println("poNumber:"+this.poNumber.trim());` – Rachel Jan 18 '11 at 20:43
  • @Rachel - I just tried it and it removes the whitespaces. Either these are not whitespaces, or you are doing something wrong that we can't see. check whether they are whitespaces - give us the ascii code of the first char. – Bozho Jan 18 '11 at 20:47
  • @Bozho: I am not sure how to find ascii code of an character ? – Rachel Jan 18 '11 at 20:49
  • @Rachel `System.out.println((int) poNumber.charAt(0));` – Bozho Jan 18 '11 at 20:51
  • a-ha. That's not a whitespace. It's a no-breaking space. – Bozho Jan 18 '11 at 21:01
  • @Bozho: How did you tackle about this situation, I want to learn from this episode. – Rachel Jan 18 '11 at 21:02
  • 2
    Awesome answer Bozho, this saved my bacon! Just as a minor tweak, I'd suggest using `replace(String.valueOf((char) 160), " ");` instead of `replace(String.valueOf((char) 160), "");` (i.e., replace the non-breaking space with a real space, which trim() can then delete). That way, if there are other non-breaking spaces in the middle of the string you're trimming they'll be replaced by normal spaces instead of blanks. – Andy Sep 06 '12 at 17:27
  • It was freaking nightmare..glad I landed at this page. – Sheetal Mohan Sharma Mar 08 '13 at 00:48
  • 3
    `replace((char) 160, ' ')` can be used instead. – marwinXXII Jun 17 '14 at 07:35
3

Are you sure you're reading the right variable for your output? You have 'poNumber', which is the original untrimmed string, and 'this.poNumber', which would get the trimmed string.

Phil
  • 2,308
  • 1
  • 18
  • 23
1

You could use this function,i did some manipulation on java trim() method and this is way better,fast and efficient than some replace() methods.

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
1

Your file may have non-ascii whitespace which is not being trimmed. For example there is a unicode character non-breaking space (U+00A0), which displays as whitespace but is not considered by trim (this is something you might see such as in a document edited in wordpad or other editors which try to "help" you.) If you look at the definition of String.trim() it removes characters that are <= ' ' (i.e. value less than or equal to 20).

So print the byte values of your string (or look at it in a hex editor) and make sure that your spaces actually are space (i.e. decimal value 20). If you need other behavior you might need to write your own trim utility function that uses a proper unicode Character.isWhiteSpace(char) check.

M. Jessup
  • 8,153
  • 1
  • 29
  • 29