-3

I have a single string as follows

one two
three
four

I would like to split this into an arrayList so that I can get

String[] g = [one,two,three,four]

I think I need to split by newline and by space but something so simple is defeating me

I have tried:

String [] bilbo=null;
List<String> temp=new ArrayList<String>();

bilbo=g.split("\\n|\\r");

for (String d:bilbo) {
    if (d!="") {
        if (d.matches("\\s")) {
            dd = d.split("\\s");
            for (String a : dd) {
                temp.add(a.trim());
            }
        } else {
            temp.add(d.trim());
        }
    }
}
Maljam
  • 6,244
  • 3
  • 17
  • 30
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125

1 Answers1

2

Instead of splitting with "\n|\r", you could simply split with "\\s+", which will cover spaces and new lines:

ArrayList<String> list = Arrays.asList(g.split("\\s+"));
Maljam
  • 6,244
  • 3
  • 17
  • 30