Patrick Kwinten Patrick Kwinten - 2 months ago 8
Java Question

create an array from elements in a string, elemets start with certain key/sign

I want to abstract an array with text strings that reside in a text, each text element starts with a certain sign or key e.g. $ or &. how can I achieve this?

so "$Huey, $Dewey, and $Louie all live in Duckcity. $Goofy and $Mickey live there too." should result in

string characters = {"Heuy","Dewey", "Louie", "Goofy","Mickey"};

Answer

Use Streams and a filter.

    String s = "$Huey, $Dewey, and $Louie all live in Duckcity. $Goofy and $Mickey live there too.";
    String[] a = 
            // Split it into words.
            Arrays.stream(s.split("[, .]"))
            // Pick only the words starting with '$'
            .filter(w -> w.startsWith("$"))
            // Remove the '$'
            .map(w -> w.substring(1))
            // Make a list.
            .collect(Collectors.toList())
            // And turn it into an array.
            .toArray(new String[0]);
    System.out.println(Arrays.toString(a));

Prints:

[Huey, Dewey, Louie, Goofy, Mickey]