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

ThreaT
  • 3,683
  • 14
  • 61
  • 103

4 Answers4

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

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

This should do it.

Makoto
  • 100,191
  • 27
  • 181
  • 221
DarthVader
  • 49,515
  • 70
  • 199
  • 295
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
  • 572,413
  • 138
  • 1,043
  • 1,132
  • 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. – ThreaT 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
  • 172,148
  • 26
  • 225
  • 324
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,215
  • 12
  • 11