1

I have a String on the variable coords which has the value of a String array, but it is not an array (outcome of toString).

String coords = "[[126,224],[255,232],[270,332],[106,444]]";

How can you create a String array from this String? An array doesn't have a #valueOf (as far as I know) and you can't easily split the characters.

Edit: I am looking for a String array which contains the four Strings as their own entries. E.g. "126,224", "255,322"..

11
  • 1
    String#split(String)? Commented May 21, 2016 at 13:33
  • May I ask why you are instantiating it as a String if you wish to immediately convert to String[] ? Commented May 21, 2016 at 13:34
  • @CássioMazzochiMolin You have to give a regex. Commented May 21, 2016 at 13:35
  • @ScottStainton In the code, I don't actually initiate the String, it is gained from a third-party library which returns a String object. Commented May 21, 2016 at 13:35
  • What should the array look like? Commented May 21, 2016 at 13:36

3 Answers 3

3

One of the easiest ways to achieve that is:

String[] array = coords.replaceAll("\\[\\[", "").replaceAll("\\]\\]", "").split("\\],\\[");

The above code replaces all [[ and ]] with an empty character and then split by ],[.

Sign up to request clarification or add additional context in comments.

Comments

2

Solution with Stream API and without replacing

Arrays.asList(coords.split("\\[\\[|]]|],\\[")).stream().filter(s -> !s.isEmpty()).forEach(System.out::println);

or in commont case

Arrays.asList(coords.split("\\[\\[|]]|],\\[")).stream()
    .filter(s -> !s.isEmpty()).forEach(s -> {
    //do whatever you want
});

Comments

0

Looking for something like this?

public class Tmp {
    public static void test() {
        String coords = "[[126,224],[255,232],[270,332],[106,444]]";
        String arr[];
        if (coords.length() < 4) {
            arr = null;
        } else {
            arr = coords.substring(2, coords.length() - 2).split("\\],\\[");
        }
        for (String str : arr) {
            System.out.printf("%s\n", str);
        }
    }

    public static void main(String[] args) {
        test();
    }
}

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.