Table of Contents
When you have a string, sometimes you want to be able to split into an array of smaller pieces.
This is most commonly done with a delimiter, such as a comma.
In this post, we'll learn how to split a string in Java using a delimiter of your choice.
How to split a string in Java
To start off, let's begin with a comma-separated string.
JAVAString string = "apples,oranges,bananas";
Now we can use the built-in method on the String class called split
to split the string into an array of strings.
This method takes a single argument, which is the delimiter to split the string on.
Let's use the split
method with a comma as the delimiter.
JAVAString string = "apples,oranges,bananas";
String[] stringArray = string.split(",");
for (String s : stringArray) {
System.out.println(s);
}
BASHapples
oranges
bananas
The second parameter is the limit, which you can use to limit the number of elements in the array.
Let's try our earlier example with a limit of 2:
JAVAString string = "apples,oranges,bananas";
String[] stringArray = string.split(",", 2);
for (String s : stringArray) {
System.out.println(s);
}
BASHapples
oranges,bananas
Instead of returning an array of length 3, we only have an array of length 2 because we limited the number of elements to 2.
Conclusion
In this post, we learned how to split a string in Java using a delimiter of your choosing.
Simply use the split
method and pass it your delimiter and an optional limit, and you'll get back an array of strings.
Thanks for reading!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js