String to string array conversion in java
To convert a String to a String array in Java, you can use the split()
method.
After running this code, arr
will now be an array with the elements {"one", "two", "three"}
.
Breaking down strings
If you want to split a string into individual characters:
This will give you an array {"e", "x", "a", "m", "p", "l", "e"}
. Be aware that prior to Java 8, this would include an initial empty string.
The manual way
Here is a more manual approach, using a for loop to populate the array:
This method allows much more control over how the strings are created.
Benefiting from libraries
Libraries like Guava can streamline this process for you:
Here, Guava takes the heavy lifting off your shoulders.
Streamlining with lambda expressions
Java 8 introduced Lambda expressions that can make your code more concise:
In this example, we're taking advantage of Java's fancy streams to create an array of strings in just a few lines.
Regular expressions with split()
For a more fine-grained control, use regular expressions with split()
:
The resulting array after splitting by &
with surrounding spaces is {"Java 11", "Java 8"}
.
Consider method visibility
When you implement these methods, be sure to consider method visibility:
The public
modifier here means this method can be called from any class in your application.
Advanced topics
Splitting without using split()
What if split()
doesn't work for your case? Resort to manual handling:
Dealing with special characters
Careful with special characters in regex:
Since .
is a special character in regex (it means "any character"), the dot needs to be escaped.
Handling empty strings
Processing empty strings requires precise handling:
Here, splitting an empty string results in an array containing a single empty string, which you may want to handle differently.
Was this article helpful?