Patrick Kwinten Patrick Kwinten - 1 year ago 67
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 Source

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.
  "[, .]"))
            // Pick only the words starting with '$'
            .filter(w -> w.startsWith("$"))
            // Remove the '$'
            .map(w -> w.substring(1))
            // Make a list.
            // And turn it into an array.
            .toArray(new String[0]);


[Huey, Dewey, Louie, Goofy, Mickey]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download