Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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)
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...