Results 1 to 5 of 5
  1. #1
    a.tajj is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default Problem with split function

    Hello

    I am using split function for the following data:

    [a1,a2,,a3,a4,,a5,,]

    Using this data I would like to end up with an array of 9 strings, meaning

    array[0]=a1
    array[1]=a2
    array[2]= {just empty or null}
    array[3]=a3
    array[4]=a4
    array[5]= {just empty or null}
    array[6] = a5
    array[7]={just empty or null}
    array[8]={just empty or null}

    The split function handles the seperators correctly if they are empty and in the middle of the string (array[2] and array[5]) but not array[7] or array[8].

    Can you please help me solve this?

    Many Thanks:confused:

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    As per the String API, the split method can take a second parameter, an int that will tell the method how many times to perform the split. If it is negative, the pattern will be applied as many times as possible. Thus you want your split to be something like:
    myString.split(",", -1); For instance:
    Java Code:
    public class Fu2
    {
      public static void main(String[] args)
      {
        String input = "a1,a2,,a3,a4,,a5,,";
        String[] tokens = input.split(",", -1);
        for (int i = 0; i < tokens.length; i++)
        {
          System.out.println("token " + i + ": " + tokens[i]);
        }
      }
    }

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

  4. #4
    a.tajj is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default

    Thank you so much for your reply. You helped me solve my problem. :)

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

Similar Threads

  1. How to split a String using split function
    By Java Tip in forum java.lang
    Replies: 4
    Last Post: 04-17-2009, 08:27 PM
  2. problem with split method
    By abhiN in forum New To Java
    Replies: 7
    Last Post: 02-10-2009, 01:54 PM
  3. Weird problem upon calling same function twice
    By alin_ms in forum New To Java
    Replies: 2
    Last Post: 12-20-2008, 06:14 PM
  4. How to split a String using split function
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 09:32 PM
  5. Function declaration problem.
    By snooze-g in forum Advanced Java
    Replies: 3
    Last Post: 07-18-2007, 09:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •