2

If I have the following string:

String string = "My \n name \n is \n John \n Doe";

And I want to separate each word and add it to an arraylist:

ArrayList<String> sentence = new ArrayList<String>();

How would I do that?

Bare in mind that the line break may not be \n - it could be anything.

Thanks

4 Answers4

12
String lines[] = String.split("\\n");

for(String line: lines) {
    sentence.add(line);
}

This should do it.

Makoto
  • 104,088
  • 27
  • 192
  • 230
DarthVader
  • 52,984
  • 76
  • 209
  • 300
6
List<String> list = Arrays.asList(string.split("\\s+"));
  • you are splitting on "any number of whitepsace symbols", which includes space, new line, etc
  • the returned list is readonly. If you need a new, writable list, use the copy-constructor
    new ArrayList(list)
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I *think* the OP wants his string breaked according to lines, not white spaces. – amit May 04 '12 at 20:41
  • \s includes new lines. And I interpreted his last sentence as it can be any other whitespace. Though I might be wrong – Bozho May 04 '12 at 20:42
  • but it also includes white spaces, what will `"My name is \n amit"` yield? – amit May 04 '12 at 20:43
  • I just updated my comment. The thing is, he wants to separate "words". So I assumed he needs any whitespace. Let's see if my assumption is correct – Bozho May 04 '12 at 20:44
  • Well then - if this is indeed the case, the answer fits. – amit May 04 '12 at 20:52
  • I'd prefer to only split by line breaks because there might be more than one word before the next line break. –  May 04 '12 at 21:03
1

You can use String.split("\\s*\n\\s*") to get a String[], and then use Arrays.asList(). It will get a List<String>, if you want an ArrayList you can use the constructor ArrayList(Collection)

String string = "My \n name \n is \n John \n Doe";
String[] arr = string.split("\\s*\n\\s*");
List<String> list = Arrays.asList(arr);

You can also use Character.LINE_SEPARATOR instead of \n.

amit
  • 175,853
  • 27
  • 231
  • 333
0
import java.util.Arrays;
import java.util.List;

public class Test
{
    public static void main( String[] args )
    {
        List < String > arrayList = Arrays.asList( "My \n name \n is \n John \n Doe".split( "\\n" ) );
        // Removes the 2 white spaces: .split( " \\n " )
    }
}
Jonathan Payne
  • 2,223
  • 13
  • 11