reesjones
reesjones

Reputation: 704

How to convert String to ArrayList<String>

Let's say I have this String -

string = "AEIOU";

and I wanted to convert it to an ArrayList<String>, where each character is it's own individual String within the ArrayList<String>

[A, E, I, O, U]

EDIT: I do NOT want to convert to ArrayList<Character> (yes, that's very straightforward and I do pay attention in class), but I DO want to convert to an ArrayList<String>.

How would I do that?

Upvotes: 0

Views: 26681

Answers (7)

Queenie Peng
Queenie Peng

Reputation: 45

Kotlin approach:

fun String.toArrayList(): ArrayList<String> {
    return ArrayList(this.split("").drop(1).dropLast(1))
}

var letterArray = "abcd".toArrayList()
print(letterArray) // arrayListOf("a", "b", "c", "d")

Upvotes: -1

christopher18
christopher18

Reputation: 23

You can do it by using the split method and setting the delimiter as an empty string like this:

ArrayList<String> strings = new ArrayList<>(Arrays.asList(string.split("")));

Upvotes: 2

Ajo Koshy
Ajo Koshy

Reputation: 1225

For a single line answer use the following code :

    Arrays.asList(string .toCharArray());

Upvotes: -1

mre
mre

Reputation: 44240

transform the String into a char array,

char[] cArray = "AEIOU".toCharArray();

and while you iterate over the array, transform each char into a String, and then add it to the list,

List<String> list = new ArrayList<String>(cArray.length);

for(char c : cArray){
    list.add(String.valueOf(c));
}

Upvotes: 6

Wes Johnson
Wes Johnson

Reputation: 69

First you have to define the arrayList and then iterate over the string and create a variable to hold the char at each point within the string. then you just use the add command. You will have to import the arraylist utility though.

String string = "AEIOU";
ArrayList<char> arrayList = new ArrayList<char>();

for (int i = 0; i < string.length; i++)
{
  char c = string.charAt(i);
  arrayList.add(c);
}

The import statement looks like : import java.util.ArrayList;

To set it as a string arrayList all you have to do is convert the char variables we gave you and convert it back to a string then add it: (And import the above statement)

ArrayList<String> arrayList = new ArrayList<String>();
String string = "AEIOU"

for (int i = 0; i < string.length; i++)
{
  char c = string.charAt(i);
  String answer = Character.toString(c);
  arrayList.add(answer);
}

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76888

Since everyone is into doing homework this evening ...

String myString = "AEIOU";
List<String> myList = new ArrayList<String>(myString.length());
for (int i = 0; i < myString.length(); i++) {
    myList.add(String.valueOf(myString.charAt(i)));
}

Upvotes: -1

AlexWien
AlexWien

Reputation: 28727

Loop and use String.charAt(i), to build the new list.

Upvotes: 2

Related Questions