ezhil
ezhil

Reputation: 1083

How to convert the string into Array in Java

I have string as [arun, joseph, sachin, kavin]. I want to replace this text as ["arun", "joseph", "sachin", "kavin"]. All the values should be in double quotes. I have tried to do this using replace method. But i could not accomplish. Can anyone help me to resolve this?

Upvotes: 1

Views: 86

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You could try this,

  • replace [, ] with an empty string.

  • Then do splitting according to the comma.

    Strings parts[] = string.replaceAll("^\\[|\\]$", "").split("\\s*,\\s*");
    
  • ^\\[|\\]$ matches the [, ] present at the start and at the end.

  • replaceAll function then replaces the matched brackets with an empty string.

  • Then by splitting the resultant string according to

\s* -> zero or more spaces

, -> comma

\s* -> zero or more spaces

will give you the desired output.

Upvotes: 2

aioobe
aioobe

Reputation: 421020

Your question is a bit unclear. Do you want to turn a string containing

[arun, joseph, sachin, kavin]

into this string

["arun", "joseph", "sachin", "kavin"]

or do you want to turn it into an actual array containing "arun", "joseph", "sachin" and "kavin"?

Regardless, this is pretty basic string manipulation. Here's what I suggest you try:

  • Use substring to get rid of the first and last character.
  • Use split to split the string on ", ".
  • If you want to add '"' before and after each component in this array, you can do

    for (int i = 0; i < array.length; i++)
        array[i] = '"' + array[i] + '"';
    

Upvotes: 3

Related Questions