0

I am new to java please help me with this issue.
I have a string lets say

adc|def|efg||hij|lmn|opq

now i split this string and store it in an array using

String output[] = stringname.split("||");

now i again need to split that based on '|' and i need something like

arr[1][]=adc,arr[2][]=def
and so on so that i can access each and every element. something like a 2 dimensional string array. I heard this could be done using Arraylist, but i am not able to figure it out. Please help.

1
  • sorry, expected is arr[0][0]=adc,arr[0][1]=def and so on. Commented Oct 4, 2013 at 5:03

3 Answers 3

1

Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:

String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
    int i=0;
    String[][] names = new String[obj.length][]; 

    for(String temp:obj){
        names[i++]=temp.split("\\|");

    }
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
               // Similarly you can fetch other elements by yourList.get(1)[index]
Sign up to request clarification or add additional context in comments.

7 Comments

Why are you escaping pipes?
I tried without escaping pipes but then its not spliting string properly. That's why I add escaping pipes and bingo..its working. :)
And where is the ArrayList part of the question?!
But how do i extract each and every string from the name array? It says null.
@R.J I forgot to paste last line. ;) @Magic - It's names array, not name, and BTW how you are accessing it?
|
0

What you can do is:

String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:

Arrays.asList(any_array);

2 Comments

U mean to say use seperate arrays to sub split it based on '|'?? but the numbe rof splits produced varies.
i meant how you can access them and according to your need you can loop around them and put them into array, arrayList whatever you want, i showed how to slit them
0

Can hardly understand your problem...

I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>

String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
    ArrayList<String> strList = new ArrayList<String>();
    for(String str:strs.split("|"))
        strList.add(str);
    res.add(strList);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.