convert string to string array

1. Overview

string Probably one of the most used types in Java.

In this tutorial, we will explore how a . how to convert string In string array (string[],

2. Introduction to the problem

There can be two scenarios of converting a string to a string array:

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

Case 1 is relatively easy to understand. For example, if we have a string “Beldung”we want to convert it string[]{“beldung”}, In other words, The converted array contains 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 depends entirely on the requirement. For example, if we expect each element in the final array to contain two adjacent characters from the input string, then given “Beldung”, We shall string[]{ “ba”, “l”, “du”, “ng” }. Later, we will see more examples.

In this tutorial, we will take this string as input:

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

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

3. Converting to Singleton Array

Since 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 Input Strings to Elements in an Array

Now, let us see how to split 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 call the input a . can break in string Array using regular expression or regex. I you string class provides split() how to do this,

Next, we’ll look at splitting our input example into an array, observing 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 with punctuation marks:

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

Point to be noted is that When we need the character class of the regex to contain the dash character, we can put it at the very beginning,

The above test shows that the input string is split into two segments in an array.

Next, let’s extract all the words from the same input string into an array of words. This is also a common problem that we can 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 split 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. Each character, including the space in the input string, is extracted as an element of the target array.

we should note String.toCharArray() Also converts the input to an array. However, the target array a. Is four array (four[]) instead of a string array (string[],,

used three examples String.split() Method to convert input strings into different string arrays. Some popular libraries, such as Guava and Apache Commons, also provide advanced string splitting functionality. We have talked about this in detail in another article.

In addition, we have several other articles to discuss how to solve various solid segmentation problems.

4.2. special parsing requirements

Sometimes we must follow a special rule to divide the input. An example can quickly illustrate this. Let’s say we have this input string:

String FLIGHT_INPUT = "20221018LH720FRAPEK";

And we expect to get this array as result:

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

Well, at first glance, this conversion logic seems ambiguous. However, if we list the definition of the input string, we will see why the above array is as 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 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 have used substring() Method to build a parser and process flight input correctly.

5. Epilogue

In this article, we learned that a . how to convert string to do 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 String.split() way. However, if we need to break down the input following a particular rule, we may want to carefully analyze the input format and implement a parser to solve the problem.

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


Leave a Comment