3

this may be pretty simple, but for some reason I am blanking right now.

Suppose I had a string "Hello I Like Sports"

How would I add each word to an arraylist (so each word is in an index in the arraylist)?

Thanks in advance!

4

8 回答 8

10
ArrayList<String> wordArrayList = new ArrayList<String>();
for(String word : "Hello I like Sports".split(" ")) {
    wordArrayList.add(word);
}
于 2013-05-24T02:51:19.097 回答
5

The first thing to do is to split that sentence up into pieces. The way to do that is to use String.split That will return an Array of Strings.

Since you want it in an ArrayList, the next thing you have to do is loop through every String in the array and add it to an ArrayList

于 2013-05-24T02:50:23.600 回答
4
String[] words = sentence.split(" ");  
list.addAll(Arrays.asList(words));
于 2013-05-24T02:51:59.130 回答
2

Try this:

public static void main(String[] args) {
        String stri="Hello I Like Sports";
        String strar[]=stri.split(" ");
        ArrayList<String> arr = new ArrayList<String>(Arrays.asList(strar));
        for(int x=0;x<arr.size();x++){
            System.out.println("Data :"+arr.get(x));
        }
    }

Output :

Data :Hello
Data :I
Data :Like
Data :Sports
于 2013-05-24T02:58:57.327 回答
1

you can use the split method of the String and split on spaces to get each word in a String array. You can then use that array to create an arrayList

String sentence ="Hello I Like Sports";
String [] words = sentence.split(" ");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(words));

String.split()

Arrays.asList()

于 2013-05-24T02:53:21.027 回答
0

First, you have to split the string, and :

Sample code :

final String str = "Hello I Like Sports";
// Create a List
final List<String> list = Arrays.asList(str.split(" "));
// Create an ArrayList
final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(str.split(" ")));

Using Arrays.asList and the ArrayList constructor avoids you to iterate on each element of the list manually.

于 2013-05-24T02:56:20.130 回答
0

A little search would have done the work.

Still I am giving a solution to this. You can use Split.

You can later add those array elements to arraylist if you require.

    String s="Hello  I like Sports";
    String[] words = s.split(" "); //getting into array
    //adding array elements to arraylist using enhanced for loop
    List<String> wordList=new ArrayList();
    for(String str:words)
    {
     wordList.add(str);
    }
于 2013-05-24T03:01:37.870 回答
0

try this code was perfect work for get all word from .txt file

reader = new BufferedReader(
    new InputStreamReader(getAssets().open("inputNews.txt")));

    // do reading, usually loop until end of file reading
    String mLine;
    while ((mLine = reader.readLine()) != null) {
        for(String word :mLine.split(" ")) {
            lst.add(word);
        }
    }
于 2017-08-29T09:23:16.833 回答