これは非常に単純かもしれませんが、何らかの理由で私は今空白にしています。
「Hello I Like Sports」という文字列があるとします。
各単語を配列リストに追加するにはどうすればよいですか (したがって、各単語は配列リストのインデックスに含まれます)。
前もって感謝します!
ArrayList<String> wordArrayList = new ArrayList<String>();
for(String word : "Hello I like Sports".split(" ")) {
wordArrayList.add(word);
}
最初に行うことは、その文を断片に分割することです。 それを行う方法は、文字列の配列を返す String.splitを使用することです。
に入れたいので、次にしなければならないことは、配列内のArrayList
すべてをループして、それをに追加することですString
ArrayList
String[] words = sentence.split(" ");
list.addAll(Arrays.asList(words));
String の split メソッドを使用し、スペースで分割して、String 配列内の各単語を取得できます。その後、その配列を使用して arrayList を作成できます
String sentence ="Hello I Like Sports";
String [] words = sentence.split(" ");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(words));
少しの検索で作業が完了したでしょう。
それでも私はこれに解決策を与えています。スプリットが使えます。
必要に応じて、これらの配列要素を後で arraylist に追加できます。
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);
}
このコードを試してみてください.txtファイルからすべての単語を取得するのに最適な作業でした
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);
}
}
まず、split
文字列を取得する必要があります。
List
、使用しますArrays.asList
ArrayList
作成しますList
。サンプルコード:
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(" ")));
Arrays.asList
とコンストラクターを使用するとArrayList
、リストの各要素を手動で反復処理する必要がなくなります。