-2

I have 2 String variables,

String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";

And I want to Split these 2 strings and store it in a single String array How to do that?

I'm trying to achieve something like this, But this will throw an exception. Is there any alternate way to do this?

String[] arr = expectedDocsTextReqA.split(":") + expectedDocsTextReqB.split(":");
Aishu
  • 1,310
  • 6
  • 28
  • 52

2 Answers2

0

When you use Split method, this creates an array of strings which cannot be resized. The solution is to convert your array of strings into a list of strings:

String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
List<String> list = new ArrayList<String>();

list.addAll(Arrays.asList(expectedDocsTextReqA.split(":")));
list.addAll(Arrays.asList(expectedDocsTextReqB.split(":")));
for (int i = 0; i < list.size(); i++)
    System.out.println(list.get(i));
Joris Bertomeu
  • 105
  • 3
  • 12
0

Probably not the most efficient way to do something like this, but here goes.

String[] split1 = expectedDocsTextReqA.split(":");
String[] split2 = expectedDocsTextReqB.split(":");

//initialize result array size.
String[] result = new String[split1.length + split2.length]; 
int index = 0;
for (int i = 0; i < split1.length; i++) { //add elements of the first array
    result[index] = split1[i]
    index++;
}
for (int i = 0; i < split2.length; i++) { //add elements of the second array
    result[index] = split2[i]
    index++;
}

edit: The List implementation by Joris is probably a more reasonable method of going about this problem.