0

I actually have a String that contains the format of String array. And I want to load that string data into the array.

String data = "{"Sam" , "14","USA","7th"}";

and the String Array

String loaded_data[][];

Thanks in advance...

3
  • What do you mean String that has a format of String array? The first line provided is trying to assign a string array to a string type which isn't correct. Commented May 31, 2020 at 14:55
  • I have updated how it is Commented May 31, 2020 at 14:57
  • is this compiling i doubt. Commented May 31, 2020 at 15:04

1 Answer 1

1

I think this is what you wanted.

Using String.split() splits the string into an string array with , regex.

    public void something() {
        String data = "{'Sam' , '14','USA','7th'}";

        data = data.substring(1, data.length() - 1); //Ignores curly brackets
        data = data.replaceAll("'", ""); //Removes apostrophes
        data = data.replaceAll(" ", ""); //Removes whitespace


        String[] loadedData = data.split(","); //Splits string -> string[]

        System.out.println(Arrays.toString(loadedData));
    }

println:

[Sam, 14, USA, 7th]
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way I can do this to String[][] instead of String[]
what are you expecting the 2D array result to be? Instead of [Sam, 14, USA, 7th] it would be? [[Sam,14],[USA,7th]]?

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.