Punter Vicky
Punter Vicky

Reputation: 17042

String Trim in Java

I have to trim (including whitespaces within the string) all the strings in a list. I have written a method to do this trim using regex. I am using strArray[i] = trimString(strArray[i]); instead of using an enhanced for loop. I assume since string is immutable this way of assigning back to the same array element is correct. Am I right?

public void trimStringArray(String[] strArray){
    if(strArray!= null && strArray.length > 0){
        for(int i=0;i<strArray.length;i++){
            strArray[i] = trimString(strArray[i]);
        }           
    }
}

Upvotes: 1

Views: 455

Answers (3)

kosa
kosa

Reputation: 66677

Yes, it is ok to do. I would add add final in method signature. By adding final you can make sure mistakenly you are not re-assigning references (added safety).

public void trimStringArray(final String[] strArray){

Upvotes: 1

NPE
NPE

Reputation: 500943

Yes, your code is correct.

Note that the strArray.length > 0 check is redundant: the loop condition will automatically take care of the case when strArray has zero length.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504122

Yes, that's fine, and you wouldn't be able to use the enhanced for loop. However, you can simplify your code by getting rid of the length > 0 check - there's no harm in it executing the loop 0 times... and personally I would usually expect the parameter to such a method to be non-null anyway, leading to code like this:

public void trimStringArray(String[] strArray) {
    Preconditions.checkNotNull(strArray);
    for(int i = 0; i < strArray.length; i++) {
        strArray[i] = trimString(strArray[i]);
    }
}

(Preconditions.checkNotNull comes from Guava in this case.)

You could leave it accepting null - but do you really have many situations where it's valid to have a null array, but you want to trim everything if it's not?

As a readability thing, I'd also encourage you to include a bit more whitespace - it's definitely a personal preference, but I know I find code with no spaces, such as this, harder to read:

for(int i=0;i<strArray.length;i++){

Upvotes: 3

Related Questions