How to Convert a String to an Array in Java
Table of Contents
Sometimes when you have a string, you will want to convert it to an array.
An example of this is when you are given a sentence and want an array of the words in the sentence.
In this post, we'll learn how to use built-in methods go from a string to an array.
How to convert a string to an array
The easiest way to convert a string to an array is to use the split
method.
This built-in string method takes the string it is called on and splits it up using a delimiter that you provide.
Let's start out with example sentence:
JAVAString sentence = "this is a sentence";
Now, let's get back an array of words by splitting the sentence on the space character:
JAVAString sentence = "this is a sentence";
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words));
BASH[this, is, a, sentence]
The delimiter can also be a regular expression, which is useful for when you have more specific needs than just splitting on a space.
JAVAString sentence = "this is a sentence";
String[] words = sentence.split("\\s");
System.out.println(Arrays.toString(words));
BASH[this, is, a, sentence]
Either way, using split
on a string and passing it your desired delimiter will return an array of strings.
Conclusion
In this post, we learned how to convert a string to an array.
Simply use the split
method on your desired string with a delimiter and it will do the job of splitting up the array for you.
Thanks for reading!
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase