+5 votes
62 views
in Tips & Tricks by (242k points)
reopened
Java: Split a string

1 Answer

+3 votes
by (1.6m points)
 
Best answer

The split function
Regular expressions

If you want to split a Java string, you can use the split function. We'll show you how to do it in our instructions..

image image

In programming, there is often a need to move data from one form to another. An example of this is breaking up strings into individual subsets. The Java standard library provides you with its own function for this purpose, which we would like to bring you closer to here.

The split function

The String class provides you with a function to split a character string into subsets. The signature of the function looks like this:

public String[] split(String regex)


The function expects a string as input parameter and returns a string array . The input parameter is a regular expression that specifies where the string should be split. The following example should help to explain this: The string numbers contains different numbers, which are separated by a minus. The member function split takes this character as an argument and returns the individual substrings

String numbers = "31-x-8-x-6-x-12-x-19-x-42";
String[] split = numbers.split("-x-"); // [31, 8, 6, 12, 19, 42]

System.out.println(split[0]); // Gibt "31" aus
System.out.println(split[1]); // Gibt "8" aus

exactly between these characters in an array . It is important that the string passed in the argument is a regular expression. This means that if a regex metacharacter is to be found, it must be preceded by a double backslash ( \\ ):

String numbers = "31[-]8[-]6[-]12[-]19[-]42";
String[] split = numbers.split("\\[-\\]"); // [31, 8, 6, 12, 19, 42]

Regex metacharacters are () {{\ ^ $ | ? * +. <> - =!

Regular expressions

For more complicated strings, it is a good idea to use regular expressions in the split function . Even if a string has different types of character strings between the substrings you are looking for, you can still identify the substrings without any problems .

String numbers = "31-=dq-8-ab-6-rt-12-xz-19-??-42";
String[] split = numbers.split("-[^0-9]*-"); // [31, 8, 6, 12, 19, 42]

The regular expression " - [^ 0-9] * - " finds all strings that are not numbers and are enclosed by two minus signs. These are exactly the strings on which the string numbers should be separated. Regular expressions can often make your life easier as a programmer, but they are not always easy to put together. If you want to learn more about regular expressions, we refer to the official introduction to regular expressions in Java . You can also look it up in the relevant chapter on the Java island .


...