-1

i have a string BusAndNo = "8|1;800|2;900|1;";

Can anyone help how do i split this string into two separate string variables and call it..

1) String Bus

2) String Number.

I am able split the semicolon

Here are codes: Currently stuck and unsure how to continue from here..

        string BusAndNo = "8|1;800|2;900|1;";
        String svcDirArray[] = BusAndNo.split(";");
        String Bus;
        String Number;

        for (int i=0; i < svcDirArray.length;i++)
        {
            for (int j = 0; j < svcDirArray[i].length(); j++) 
            {
                svcDirArray[i].split("|");

            }
        }
BlueTree
  • 91
  • 14

2 Answers2

2

It looks like you are attempting to iterate through a two dimensional array, but you have a one dimensional array. Skip the inner for loop:

    for (int i=0; i < svcDirArray.length;i++)
    {     
        String busAndNo[] = svcDirArray[i].split("\\|");
        //bus = busAndNo[0], No = busAndNo[1]
    }
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Ryan
  • 2,058
  • 1
  • 15
  • 29
1
String busAndNo = "8|1;800|2;900|1;";
String[] svcDirArray = busAndNo.split(";");
String bus;
String number;

for (int i=0; i < svcDirArray.length;i++)
{
    String[] busNumber = svcDirArray[i].split("\\|");
    bus = busNumber[0];
    number = busNumber[1];
    System.out.println(bus+" = "+number);
}
osallou
  • 154
  • 6
  • If you are wondering why you are getting down-voted it is because your code will not compile, and even it we correct this minor compilation problems it will still not work (visit duplicate question to see why). – Pshemo Aug 18 '15 at 20:26
  • no problem. I fixed anyway the code to get correct compilation. I wanted to show the logic and did not pay attention to details.. my fault. – osallou Aug 18 '15 at 21:04
  • Good for you. Also remember that for many people details matters because they help us avoid unnecessary confusion and problems. So in the future try to be as specific as possible. (Unless you are helping to solve homework question. In that case feel free to leave open as many details as you want. This way OP will have something to wonder about, which will help him understand/remember topic better.) – Pshemo Aug 18 '15 at 21:19