-1

Let's say I've got a string with three strings looking like this:

String s = "[object1,object2,object3]";

How do I convert this to a String array which looks like this:

String[] ary = {"object1", "object2", "object3"};

Also mind that each string item (object1, object2 and object3) may also contain additional comma (,) characters.

Tom
  • 16,842
  • 17
  • 45
  • 54
Mark Tyers
  • 93
  • 9
  • Are those just string values (`"object1"`) or are they meant to represent variable names? – Sotirios Delimanolis Jun 24 '16 at 15:44
  • @SotiriosDelimanolis Just string values. – Mark Tyers Jun 24 '16 at 15:45
  • @Zeromus I rejected your edit suggestion for two reasons: changing the items to "a", "b" and "c" isn't helpful and calling them "character" is also misleading, since each item is more than just a single character. But it is very nice to see, that you like to help to improve questions on this page. Please keep doing that. – Tom Jun 24 '16 at 16:03

4 Answers4

2

just use the split method String[] str = s.split(","); if you want the "[ ]" out use the string.replace method to replace "[]" with ""

Seek Addo
  • 1,871
  • 2
  • 18
  • 30
  • either this or use a regex – Zeromus Jun 24 '16 at 15:47
  • @Zeromus Alright, but what if my string already contains commas like ","? Lets say I have converted an array (with jsons converted to strings) to a string, and then I want to convert it back? – Mark Tyers Jun 24 '16 at 15:47
  • @MarkTyers Then it is obiviously impossible to split these strings. – Tom Jun 24 '16 at 15:49
  • 1
    @MarkTyers do you mean "object,1,object,2,object,3" then is impossible as Tom said. you need to be clear what you want to achieve with this – Seek Addo Jun 24 '16 at 15:51
  • 1
    @MarkTyers *"Lets say I have converted an array (with jsons converted to strings) to a string, and then I want to convert it back?"* If this is the real reason why you ask this question, then say that in the question and provide a proper example? This would result in better answers for your use-case. – Tom Jun 24 '16 at 16:05
0

To do the stuff in your situation you can do

String[] ary = s.substring(1, s.length() -1).split(",");

If there is no "[" and "]" just remove the substring call

DamienB
  • 419
  • 1
  • 6
  • 20
0

I assume you want don't want the outer [], you could use replace/split or substring/split

String myArray[] = s.replace("[","").replace("]","").split(",");

Or

String myArray[] = s.substring(1, s.length() -1 ).split(",");
Abubakkar
  • 15,488
  • 8
  • 55
  • 83
0

See the code below with comments to explain what each does.

s = s.replace("[","").replace("]},""); //remove the brackets
String[] ary = s.split(",");           //split the string around commas
nhouser9
  • 6,730
  • 3
  • 21
  • 42