How to split string java

How to split string java

How to split a string in Java

By mkyong | Last updated: February 9, 2022

Viewed: 334,494 (+540 pv/w)

In Java, we can use String#split() to split a string.

Table of contents

1. Split a string (default)

1.2 We can use String#contains to test if the string contains certain characters or delimiters before splitting the string.

2. Split a string and retain the delimiter

The String#spring accepts regex as an argument, and we can also use regex lookahead, lookbehind or lookaround to retain the delimiter.

2.1 Below is a positive lookahead example, the delimiter at the right-hand side.

2.2 Below is a positive lookbehind example, the delimiter at the left-hand side.

2.3 A full example.

3. Split a string and limit the split output

3.1 The below example try to split a string and limit the output into three strings; the last string contains the remaining inputs after the last matched delimiter (split character).

3.2 The below code snippets try to split a string and limit the output into two strings.

4. Split a string by special regex characters

This section talks about escaping the special regex characters as a delimiter.

4.1 Special regex characters

The special regex characters have special meaning as follow:

P.S Both the closing square bracket ] and closing curly brace > is an ordinary character, no need to escape.

4.2 Escaping the special regex characters

If we want to split a string using one of the special regex characters as the delimiter, we must escape it.

For example, if we want to split a string by a vertical bar or pipe symbol | (special regex character), which means or in the regex, we must escape the | symbol using one of the following ways:

4.3 Split a string by a pipe symbol “|”

How to Split a String in Java

Sometimes we need to split a string in programming. We suggest String.split (), StringTokenizer, and Pattern.compile () methods.

Spliting a String in Java

The output for this will be like this:

Result

Note: Change regex to come to a different result:
E.g. for («e») regex the result will we like this:

There are many ways to split a string in Java. The most common way is using the split() method which is used to split a string into an array of sub-strings and returns the new array.

1. Using String.split ()

The string split() method breaks a given string around matches of the given regular expression. There are two variants of split() method in Java:

This method takes a regular expression as a parameter and breaks the given string around matches of this regular expression regex. By default limit is 0.

Parameter for this is: regex (a delimiting regular expression).

It returns an array of strings calculated by splitting the given string.

Example

Parameters for this are: regex (the delimiting regular expression) and limit (controls the number of times the pattern is applied and therefore affects the length of the resulting array).

This returns the array of strings counted by splitting this string around matches of the given regular expression.

Example

The output for the given example will be like this:

Result

Let’s see another example:

Example

The output will be the following:

Result

Result

Output for this will be like this:

Result

2. Using StringTokenizer

In Java, the string tokenizer allows breaking a string into tokens. You can also get the number of tokens inside string object.

Example

Result

Note: You can specify the delimiter that is used to split the string. In the above example we have set the delimiter as space (”).

It is also possible to use StringTokenizer with multiple delimiters.

Example

Result

3. Using Pattern.compile ()

It returns the array of strings computed by splitting the input around matches of the pattern.

Split a String in Java

Last modified: October 30, 2019

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

> CHECK OUT THE COURSE

1. Introduction

Splitting Strings is a very frequent operation; this quick tutorial is focused on some of the API we can use to do this simply in Java.

2. String.split()

Let’s start with the core library – the String class itself offers a split() method – which is very convenient and sufficient for most scenarios. It simply splits the given String based on the delimiter, returning an array of Strings.

Let us look at some examples. We’ll start with splitting by a comma:

Let’s split by a whitespace:

Let’s also split by a dot:

Let’s now split by multiple characters – a comma, space, and hyphen through regex:

3. StringUtils.split()

Apache’s common lang package provides a StringUtils class – which contains a null-safe split() method, that splits using whitespace as the default delimiter:

Furthermore, it ignores extra spaces:

4. Splitter.split()

Finally, there’s a nice Splitter fluent API in Guava as well:

5. Split and Trim

Sometimes a given String contains some leading, trailing, or extra spaces around the delimiter. Let’s see how we can handle splitting the input and trimming the results in one go.

Let’s say we have this as an input:

To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex:

Here, trim() method removes leading and trailing spaces in the input string, and the regex itself handles the extra spaces around delimiter.

We can achieve the same result by using Java 8 Stream features:

6. Conclusion

String.split() is generally enough. However, for more complex cases we can utilize Apache’s commons-lang based StringUtils class, or the clean and flexible Guava APIs.

And, as always, the code for the article is available over on GitHub.

How to Split a String in Java

Introduction

Oftentimes, we are faced with a situation where we need to split a string at some specific character or substring, to derive some useful information from it.

For example, we might want to split a phone number on the country code or data imported from a CSV file.

In this article, we’ll cover how to split a String in Java.

The split() Method (Without a Limit)

This method takes one String parameter, in regular expression (regex) format. This method splits the string around the matches of the given regular expression.

The syntax for this method is:

Where the regex parameter represents the delimiter, i.e. based on what we’ll split our string. Keep in mind that this parameter doesn’t need to be anything complicated, Java simply provides the option of using regular expressions.

For example, let’s see how we can split this String into two separate names:

We can simply use a character/substring instead of an actual regular expression. Of course, there are certain special characters in regex which we need to keep in mind, and escape them in case we want their literal value.

Once the string is split, the result is returned as an array of Strings. Strings in the returned array appear in the same order as in the original string.

The results are packed in the String array. To retrieve the separate names, we can access each element:

This results in:

Keep in mind, this method will split the string on all occurrences of the delimiter. For example, we can have a CSV formatted input:

This results in:

Java split() Method (With a Limit)

The limit parameter can take one of three forms, i.e it can either be greater than, less than or above zero. Let’s take a look at what each of these situations represents:

Positive Limit Value

Let’s take a look at some examples of using different limits. Firstly, a positive limit value:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If we used a negative limit on this same String:

The String will be split as many times as possible, and the trailing empty strings would be added to the array:

This would give us:

Note on Special Characters

As we mentioned earlier, the regex parameter passed as the delimiter in the split() method is a regular expression. We have to make sure to escape special characters if we want to use their literal value as a delimiter. For example, the * character means «one or more instances of the following character(s)».

Splits the string variable at the | character. We use two backlashes here since we need to first escape the Java-meaning of the backlash, so the backslash can be applied to the | character.

Instead of this, we can use a regex character set This refers to putting the special characters to be escaped inside square brackets. This way, the special characters are treated as normal characters. For example, we could use a | as a delimiter by saying:

Yet another way to escape special characters is to use Pattern.quote() :

Conclusion

The split() method of the Java String class is a very useful and often used tool. Most data, especially that obtained from reading files would require some amount of pre-processing, such as splitting the string, to obtain meaningful information from it.

In this article, we’ve gone over how to split strings in Java.

How to split a String by space

I need to split my String by spaces. For this I tried:

But it doesn’t seem to work.

How to split string java. Смотреть фото How to split string java. Смотреть картинку How to split string java. Картинка про How to split string java. Фото How to split string java

17 Answers 17

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

What you have should work. If, however, the spaces provided are defaulting to. something else? You can use the whitespace regex:

This will cause any number of consecutive spaces to split your string into tokens.

How to split string java. Смотреть фото How to split string java. Смотреть картинку How to split string java. Картинка про How to split string java. Фото How to split string java

While the accepted answer is good, be aware that you will end up with a leading empty string if your input string starts with a white space. For example, with:

The result will be:

So you might want to trim your string before splitting it:

Instead, you can use \p but you need to enable unicode character support as well which the regular split won’t do. For example, this will work: Pattern.compile(«\\p«, UNICODE_CHARACTER_CLASS).split(words) but it won’t do the trim part.

The following demonstrates the problem and provides a solution. It is far from optimal to rely on regex for this, but now that Java has 8bit / 16bit byte representation, an efficient solution for this becomes quite long.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *