简体   繁体   中英

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]);
        }           
    }
}

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++){

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.

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){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM