Evan Sanderson
Evan Sanderson

Reputation: 105

Is there an easier way to split strings than by using arrays?

I have been using arrays to split my Strings. This is starting to become very tedious as my program continues to expand. Is there an easier way to do this without using arrays? I have been using arrays to individually store each char. can I store multiple chars, maybe a String, in an array?

Upvotes: 1

Views: 144

Answers (3)

WIllJBD
WIllJBD

Reputation: 6164

I have been using arrays to individually store each char. can I store multiple chars, maybe a String, in an array?

Yes you can.

If you are looking for more helper methods, and easy functions that will help return string arrays and not just char arrays. Check out the Apache StringUtils

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

Also you can use a 2d char array

char[][]

Or you can just use your String arrays

String[]

Regardless the StringUtils will have most everything you could need. If you find yourself copy pasting logic a lot, or writing the same kind of splitting logic again and again, wrap it in a function and just call that.

Upvotes: 1

Paul Vargas
Paul Vargas

Reputation: 42010

Using the class com.google.common.base.Splitter of Google Guava :

List<String> list = Splitter.on(',').splitToList("foo,bar,qux");

Or:

Iterable<String> iterator = Splitter.on(',').split("foo,bar,qux");

Upvotes: 0

Georgian
Georgian

Reputation: 8960

I can't think of an easier way to split a String than String#split(",").

If arrays annoy you, you can simply do the following

List<String> splitList = Arrays.asList(theString.split(","));

because the list is more flexible.

If this doesn't satisfy your question, you should be more specific.

(I've given the comma regex as example)

Upvotes: 3

Related Questions