0 votes
1 view
in Java by (3.9k points)

I have a String with an unknown length that looks something like this

"dog, cat, bear, elephant, ..., giraffe"

What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList?

For example

List<String> strings = new ArrayList<Strings>();

// Add the data here so strings.get(0) would be equal to "dog",

// strings.get(1) would be equal to "cat" and so forth.

1 Answer

0 votes
by (46.1k points)

A small improvement: above solutions will not remove leading or trailing spaces in the actual String. It's better to call trim before calling split. Instead of this,

 String[] animalsArray = animals.split("\\s*,\\s*");

use

 String[] animalsArray = animals.trim().split("\\s*,\\s*");

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Java by tara92 (920 points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...