Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. How to remove white space on array

Tags:

java

For example I split a string "+name" by +. I got an white space" " and the "name" in the array(this doesn't happen if my string is "name+").

t="+name";
String[] temp=t.split("\\+");

the above code produces

temp[0]=" "
temp[1]=name

I only wants to get "name" without whitespace..

Also if t="name+" then temp[0]=name. I'm wondering what is difference between name+ and +name. Why do I get different output.

like image 227
John Avatar asked Dec 12 '12 05:12

John


3 Answers

simply loop thru the items in array like the one below and remove white space

for (int i = 0; i < temp.length; i++){
    temp[i] = if(!temp[i].trim().equals("") || temp[i]!=null)temp[i].trim();
}
like image 81
Murali N Avatar answered Nov 17 '22 14:11

Murali N


The value of the first array item is not a space (" ") but an empty string (""). The following snippet demonstrates the behaviour and provides a workaround: I simply strip leading delimiters from the input. Note, that this should never be used for processing csv files, because a leading delimiter will create an empty column value which is usually wanted.

    for (String s : "+name".split("\\+")) {
        System.out.printf("'%s'%n", s);
    }

    System.out.println();

    for (String s : "name+".split("\\+")) {
        System.out.printf("'%s'%n", s);
    }

    System.out.println();

    for (String s : "+name".replaceAll("^\\+", "").split("\\+")) {
        System.out.printf("'%s'%n", s);
    }
like image 26
Andreas Dolk Avatar answered Nov 17 '22 15:11

Andreas Dolk


You get the extra element for "+name"'s case is because of non-empty value "name" after the delimiter.

The split() function only "trims" the trailing delimiters that result to empty elements at the end of an array. See JavaSE Manual.

Examples of .split("\\+") output:

"+++++"     = { }                // zero length array because all are trailing delimiters
"+name+"    = { "", "name" }     // trailing delimiter removed
"name+++++" = { "name" }         // trailing delimiter removed
"name+"     = { "name" }         // trailing delimiter removed
"++name+"   = { "", "", "name" } // trailing delimiter removed

I would suggest preventing to have those extra delimiters on both ends rather than cleaning up afterwards.

like image 1
Ianthe the Duke of Nukem Avatar answered Nov 17 '22 13:11

Ianthe the Duke of Nukem