Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

String is probably one of the most commonly used types in Java.

In this tutorial, we’ll explore how to convert a String into a String array (String[]).

2. Introduction to the Problem

Converting a string to a string array could have two scenarios:

  • converting the string to a singleton array (an array with only one single element)
  • breaking the string into elements of an array following a particular rule

Case 1 is relatively easy to understand. For example, if we have a string “baeldung”, we want to convert it to String[]{ “baeldung” }. In other words, the converted array has only one element, which is the input string itself.

For case 2, we need to break the input string into pieces. However, how the result should be is entirely dependent on the requirement. For example, if we expect each element in the final array contains two adjacent characters from the input string, given “baeldung”, we’ll have String[]{ “ba”, “el”, “du”, “ng” }. Later, we’ll see more examples.

In this tutorial, we’ll take this string as the input:

String INPUT = "Hi there, nice to meet you!";

Of course, we’ll cover both conversion scenarios. Further, for simplicity, we’ll use unit test assertions to verify whether our solutions work as expected.

3. Converting to a Singleton Array

As the input string will be the only element in the target array, we can simply initialize an array using the input string to solve the problem:

String[] myArray = new String[] { INPUT };
assertArrayEquals(new String[] { "Hi there, nice to meet you!" }, myArray);

Then, if we run the test, it passes.

4. Converting the Input String Into Elements in an Array

Now, let’s see how to break the input string into segments.

4.1. Using the String‘s split() Method

We often need to work with input strings in specific patterns. In this case, we can break the inputs into a String array using regular expressions or regexJava’s String class provides the split() method to do this job.

Next, we’ll address splitting our input example into an array following a few different requirements.

First, let’s say we want to split the input sentence into an array of clauses. To solve this problem, we can split the input string by punctuation marks:

String[] myArray = INPUT.split("[-,.!;?]\\s*" );
assertArrayEquals(new String[] { "Hi there", "nice to meet you" }, myArray);

It’s worth mentioning that when we need a regex’s character class to contain a dash character, we can put it at the very beginning.

The test above shows that the input string is broken into two clauses in an array.

Next, let’s extract all words from the same input string into an array of words. This is also a common problem we may face in the real world.

To get the word array, we can split the input by non-word characters (\W+):

String[] myArray = INPUT.split("\\W+");
assertArrayEquals(new String[] { "Hi", "there", "nice", "to", "meet", "you" }, myArray);

Finally, let’s break the input string into characters:

String[] myArray = INPUT.split("");
assertArrayEquals(new String[] {
    "H", "i", " ", "t", "h", "e", "r", "e", ",", " ",
    "n", "i", "c", "e", " ", "t", "o", " ", "m", "e", "e", "t", " ", "y", "o", "u", "!"
}, myArray);

As the code above shows, we use an empty string (zero width) as the regex. Every character, including the space in the input string, is extracted as an element of the target array.

We should note the String.toCharArray() converts the input to an array too. However, the target array is a char array (char[]) instead of a String array (String[]).

The three examples used the String.split() method to convert the input string to different string arrays. Some popular libraries, such as Guava and Apache Commons, also provide enhanced string split functionalities. We’ve talked about that in another article in detail.

Furthermore, we have many other articles to discuss how to solve different concrete splitting problems.

4.2. Special Parsing Requirements

Sometimes we must follow a particular rule to split the input. An example can quickly clarify it. Let’s say we have this input string:

String FLIGHT_INPUT = "20221018LH720FRAPEK";

And we expect to get this array as a result:

{ "20221018", "LH720", "FRA", "PEK" }

Well, at the first glance, this conversion logic looks obscure. However, if we list the definition of the input string, we’ll see why the array above is expected:

[date][Flight number][Airport from][Airport to]
- date: YYYY-MM-DD; length:8
- Flight number; length: variable
- Airport From: IATA airport code, length:3
- Airport To: IATA airport code, length:3

As we can see, sometimes we need to parse the input string following a pretty special rule. In that case, we need to analyze the requirement and implement a parser:

String dateStr = FLIGHT_INPUT.substring(0, 8);
String flightNo = FLIGHT_INPUT.substring(8, FLIGHT_INPUT.length() - 6);
int airportStart = dateStr.length() + flightNo.length();
String from = FLIGHT_INPUT.substring(airportStart, airportStart + 3);
String to = FLIGHT_INPUT.substring(airportStart + 3);
                                                                               
String[] myArray = new String[] { dateStr, flightNo, from, to };
assertArrayEquals(new String[] { "20221018", "LH720", "FRA", "PEK" }, myArray);

As the code above shows, we’ve used the substring() method to build a parser and processed the flight input correctly.

5. Conclusion

In this article, we’ve learned how to convert a String to a String array in Java.

Simply put, converting a string to a singleton array is pretty straightforward. If we need to break the given string into segments, we can turn to the String.split() method. However, if we need to break the input following a particular rule, we may want to analyze the input format carefully and implement a parser to solve the problem.

As always, the full code used in the article is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.