5

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.

0

7 Answers 7

3

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();
}
6
  • is this able to trim the element if the element itself is white space? or it only remove the white space if the string contains white
    – John
    Dec 12, 2012 at 5:39
  • it only removes the white space
    – Murali N
    Dec 12, 2012 at 5:39
  • It produces null value instead of white space in the array.
    – John
    Dec 12, 2012 at 5:52
  • ok..do one thing just check for null's.Replace this one if(array[i].trim().equals("")){ with this one if(array[i] == null){
    – Murali N
    Dec 12, 2012 at 5:54
  • still null value. I don't know why I get white space when I split the string"+name" but doesn't get the white space for string"name+".
    – John
    Dec 12, 2012 at 6:03
1

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);
    }
2
  • what if the the string is "+++++name" or "firstname+++lastname" but I only want the name and firstname lastname. is there any good way to handle this?
    – John
    Dec 12, 2012 at 6:46
  • Sure. The delimiter is nothing but a regular expression. Use \\++ if you want to split around one or more plusses. Dec 12, 2012 at 7:55
1

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.

0
0

to remove white space

str.replaceAll("\\W","").
4
  • This doesn't work because "+name" doesn't have white space. but when split the "+name" by + I got a white space in the array
    – John
    Dec 12, 2012 at 5:43
  • you are removing white space from your string then your are spiting using loop. Dec 12, 2012 at 5:49
  • this string "+name" doesn't have white space.
    – John
    Dec 12, 2012 at 5:50
  • but when I split this string by array=string.split("\\+"). I got a white space in array[0]
    – John
    Dec 12, 2012 at 5:51
0

String yourString = "name +";
yourString = yourString.replaceAll("\\W", "");
yourArray = yourString.split("\\+");

2
  • This doesn't work because "+name" doesn't have white space. but when split the "+name" by + I got a white space in the arra
    – John
    Dec 12, 2012 at 5:45
  • Not sure why it doesn't work with you. But if you try to take a look at this code, it actually works. String str = "name +"; str = str.replaceAll("\\W", ""); String[] array = str.split("\\+"); for( int i = 0; i < array.length; i++){ System.out.println(array[i]); } Dec 12, 2012 at 5:46
0

For a one liner :

String temp[] = t.replaceAll("(^\\++)?(\\+)?(\\+*)?", "$2").split("\\+");

This will replace all multiple plus signs by one, or a plus sign at the start by empty String, and then split on plus signs. Which will basically eliminate empty Strings in the result.

split(String regex) is equivalent to split(String regex, int limit) with limit = 0. And the documentation of the latter states :

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Which is why a '+' at the start works differently than a '+' at the end

0

You might want to give guavas Splitter a try. It has a nice fluent api to deal with emptyStrings, trim(), etc.

@Test
public void test() {
    final String t1 = "+name";
    final String t2 = "name+";

    assertThat(split(t1), hasSize(1));
    assertThat(split(t1).get(0), is("name"));

    assertThat(split(t2), hasSize(1));
    assertThat(split(t2).get(0), is("name"));
}

private List<String> split(final String sequence) {
    final Splitter splitter = Splitter.on("+").omitEmptyStrings().trimResults();
    return Lists.newArrayList(splitter.split(sequence));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.