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
String lines[] = String.split("\\n");
for(String line: lines) {
sentence.add(line);
}
This should do it.
List<String> list = Arrays.asList(string.split("\\s+"));
new ArrayList(list)
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
.
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 " )
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.