Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Efficiency! Custom Serialization

Hudson Kim
Hudson Kim
2,965 Points

What is the Split() method?

So what exactly is the split method and what do you input into it such as \|?

1 Answer

The split() functions splits a single String into an array of multiple Strings. The parameter tells the method where to split. For example my String is "Agatha,Mark,Carrie" and I want to split at the comma.

String names = "Agatha,Mark,Carrie";

String[] namesAsArray = names.split(","); 

Now the variable namesAsArray contains {"Agatha", "Mark", "Carrie"} . It means you can treat each name as a separate entity, instead of having a single string.

Here is the doc: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

The split() function accepts regex patterns, which allows you to match different characters or character patterns. '\\|' is how you tell the function to split at the character | (the reson for the '\\' is because | is a special character in regex).

Hudson Kim
Hudson Kim
2,965 Points

Thanks Livia for your answer!