Java using split method

Java String split() Method with examples

Java String split method is used for splitting a String into substrings based on the given delimiter or regular expression.

For example:

Input String: [email protected] Regular Expression: @ Output Substrings:

Java String Split Method

Java Split Method Examples

We have two variants of split() method in String class.

1. String[] split(String regex) : It returns an array of strings after splitting an input String based on the delimiting regular expression.

2. String[] split(String regex, int limit) : This method is used when you want to limit the number of substrings. The only difference between this variant and above variant is that it limits the number of strings returned after split up. For example: split(«anydelimiter», 3) would return the array of only 3 strings even if there can be more than three substrings.

What if limit is entered as a negative number?
If the limit is negative then the returned string array would contain all the substrings including the trailing empty strings, however if the limit is zero then the returned string array would contains all the substrings excluding the trailing empty Strings.

Читайте также:  Java can you cast null to

It throws PatternSyntaxException if the syntax of specified regular expression is not valid.

String split() method Example

If the limit is not defined:

Java String split method

If positive limit is specified in the split() method: Here the limit is specified as 2 so the split method returns only two substrings.

String split strings with a limit

If limit is specified as a negative number: As you can see that when the limit is negative, it included the trailing empty strings in the output. See the output screenshot below.

String split when limit is set to negative

Limit is set to zero: This will exclude the trailing empty strings.

output

Difference between zero and negative limit in split() method:

  • If the limit in split() is set to zero, it outputs all the substrings but exclude trailing empty strings if present.
  • If the limit in split() is set to a negative number, it outputs all the substrings including the trailing empty strings if present.

Java String split() method with multiple delimiters

Let’s see how we can pass multiple delimiters while using split() method. In this example we are splitting input string based on multiple special characters.

Number of substrings: 7 Str[0]: Str[1]:ab Str[2]:gh Str[3]:bc Str[4]:pq Str[5]:kk Str[6]:bb

Lets practice few more examples:

Java Split String Examples

Example 1: Split string using word as delimiter

Here, a string (a word) is used as a delimiter in split() method.

Example 2: Split string by space

String[] strArray = str.split("\\s+");
Input: "Text with spaces"; Output: ["Text", "with", "spaces"]

Example 3: Split string by pipe

String[] strArray = str.split("\\|");
Input: "Text1|Text2|Text3"; Output: ["Text1", "Text2", "Text3"]

Example 4: Split string by dot ( . )

String[] strArray = str.split("\\.");

You can split string by dot ( . ) using \\. regex in split method.

Input: "Just.a.Simple.String"; Output: ["Just", "a", "Simple", "String"]

Example 5: Split string into array of characters

String[] strArray = str.split("(?!^)");

The ?! part in this regex is negative assertion, which it works like a not operator in the context of regular expression. The ^ is to match the beginning of the string. Together it matches any character that is not the beginning of the string, which means it splits the string on every character.

Input: "String"; Output: ["S", "t", "r", "i", "n", "g"]

Example 6: Split string by capital letters

String[] strArray = str.split("(?=\\p)");

\p is a shorthand for \p . This regex matches uppercase letter. The extra backslash is to escape the sequence. This regex split string by capital letters.

Input: "BeginnersBook.com"; Output: ["Beginners", "Book.com"]

Example 7: Split string by newline

String[] str = str.split(System.lineSeparator());

This is one of the best way to split string by newline as this is a system independent approach. The lineSeparator() method returns the character sequence for the underlying system.

Example 8: Split string by comma

String[] strArray = str.split(",");

To split the string by comma, you can pass , special character in the split() method as shown above.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Is it right to say that 28 is present at array1[0], 12 at array1[1] and 2013 at array1[2]?
I am really confused right now.Please help.

It would be helpful to include some examples that require use of the escape characters and which characters need them. It is one thing I was looking for. Once I realized that “|” needed “\\|”, my split worked like a champ. Thanks for showing these using small code bits. It really does make a difference.

Источник

Java using split method

если не хотите экранировать или не знаете, надо ли, просто пишите text.split(Pattern.quote(«<нужный знак>«)); Тогда значение всегда будет строковым и не касаться регулярок. Ну и если нет автоимпорта, то не забудьте импортировать java.util.regex.Pattern

Статья класс, можно добавить, что в качестве параметра split принимает и сразу несколько разделителей

 String str = "Амо/ре.амо,ре"; String[] words = str.split("[/\\.,]"); // Амо ре амо ре 

А если нет разделителей, но есть сплошная строка длиной N символов, и нужно разделить ее, допустим, на число M ? То как в этом случае быть?

Когда я в первый раз прочитал данную статью, ничего не понял и посчитал данную статью бесполезной. А на тот момент я изучал первый месяц. И сейчас, спустя еще 2 месяца я наконец то понял что тут написано) И могу теперь смело сказать что да, статья полезная.

А если в задаче разделитель вводится с клавиатуры, то как добавить\\ чтоб ошибки зарезервированного знака не было?

По-моему, зря ничего не сказано про то, что точка ( «.») не может служить разделителем, в отличие от запятой например. И её надо обозначать слэшами — («\\.»)

JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

Источник

Java String split() Method

Java String split() method returns a String array. It accepts string argument and treats it as regular expression. Then the string is split around the matches found.

String split() Method Syntax

There are two overloaded split() methods.

  1. public String[] split(String regex, int limit) : The limit argument defines the result string array size. If the limit is 0 or negative then all possible splits are part of the result string array.
  2. public String[] split(String regex) : This is a shortcut method to split the string into maximum possible elements. This method calls split(regex, 0) method.

Important Points About String split() Method

  • The result string array contains the strings in the order of their appearance in this string.
  • If there are no matches, then the result string array contains a single string. The string element has the same value as this string.
  • We can use split() method to convert CSV data into a string array.
  • Trailing empty strings are not included in the result. For example, «A1B2C3D4E5».split(«7») will result in the string array [A, B, C, D, E] .

Java String split() Examples

Let’s look at some simple examples of split() method.

package net.javastring.strings; import java.util.Arrays; public class JavaStringSplit < public static void main(String[] args) < String s = "Hello World 2019"; String[] words = s.split(" "); System.out.println(Arrays.toString(words)); String s1 = "A1B2C3D4E5"; String[] characters = s1.split("3"); System.out.println(Arrays.toString(characters)); String[] twoWordsArray = s.split(" ", 2); System.out.println(Arrays.toString(twoWordsArray)); System.out.println(Arrays.toString(s.split("X", 2))); String s2 = "A1B2C3D "; System.out.println(Arrays.toString(s2.split("1"))); >>
[Hello, World, 2019] [A, B, C, D, E] [Hello, World 2019] [Hello World 2019] [A, B, C, D ]

String split() Examples using JShell

We can run some examples using jshell too.

jshell> "Hello World 2019".split(" "); $34 ==> String[3] < "Hello", "World", "2019" >jshell> "A1B2C3D4E5".split("8"); $35 ==> String[5] < "A", "B", "C", "D", "E" >jshell> "Hello World 2019".split(" ", 2); $36 ==> String[2] < "Hello", "World 2019" >jshell> " A1B2C3D ".split("6"); $37 ==> String[4] < " A", "B", "C", "D " >jshell>

Java String Split Examples

Reference

Источник

Оцените статью