- Split string to string array java
- Convert String to String[] in Java
- How to split String into Array [Practical Examples]
- Getting started with Split String into Array Examples
- Syntax
- Examples to split String into Array
- Example 1 : Split String into Array with given delimiter
- Example 2 : Split String into Array with delimiter and limit
- Example 3 : Split String into Array with another string as a delimiter
- Example 4 : Split String into Array with multiple delimiters
- Example 5 : Split the String without using built-in split function
- Example 6 : Split the content read from the file line wise
- Example 7 : Count the number of words in a string using split method
- Summary
- References
- Leave a Comment Cancel reply
- Java Tutorial
- Java String split()
Split string to string array java
если не хотите экранировать или не знаете, надо ли, просто пишите 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. Больше подробностей — в нашем Пользовательском соглашении.
Convert String to String[] in Java
Java examples to convert a string into string array using String.split() and java.util.regex.Pattern .slipt() methods.
String blogName = "how to do in java"; String[] words = blogName.split(" "); //[how, to, do, in, java] Pattern pattern = Pattern.compile(" "); String[] words = pattern.split(blogName); //[how, to, do, in, java]
Use split() method to split a string into tokens by passing a delimiter (or regex) as method argument.
String names = "alex,brian,charles,david"; String[] namesArray = names.split(","); //[alex, brian, charles, david]
In Java, Pattern is the compiled representation of a regular expression. Use Pattern.split() method to convert string to string array, and using the pattern as the delimiter.
String names = "alex,brian,charles,david"; Pattern pattern = Pattern.compile(","); String[] namesArray = pattern.split( names ); //[alex, brian, charles, david]
Use String.join() method to create a string from String array. You need to pass two method arguments i.e.
- delimiter – the delimiter that separates each element
- array elements – the elements to join together
The join() will then return a new string that is composed of the ‘array elements’ separated by the ‘delimiter’.
String[] tokens = ; String blogName1 = String.join("", tokens); //HowToDoInJava String blogName2 = String.join(" ", tokens); //How To Do In Java String blogName3 = String.join("-", tokens); //How-To-Do-In-Java
Drop me your questions in the comments section.
How to split String into Array [Practical Examples]
Getting started with Split String into Array Examples
In many real time applications, we may need to work on the words of the string rather than the whole strings. In this case, we will need to split the string into its equivalent words. Java provides the split() function in a string class that helps in splitting the string into an array of string values. There are variety of ways in which we can use the split function depending on our requirement.
Syntax
The split function is used in two different variants as shown below.
split(String regex) String[] split(String regex, int limit)
The first one is used to splits this string around matches of the given regular expression. Whereas, in the second variant an additional parameter limit specifies the number of times the regex will be used as a splitting character. Here, regex parameter is a delimiter used to split the words.
Examples to split String into Array
Example 1 : Split String into Array with given delimiter
In this example, we are simply splitting the string using the space as a delimiter. However, we are not limiting to the number of times delimiter is used. Therefore, it will split whole string into an Array of strings.
// Program to split String into array using space delimiter public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Welcome to the world of java programming "; // Using split function String[] a = s.split(" "); // Printing the resultant array for (String i: a) System.out.println(i); >>
Welcome to the world of java programming
Example 2 : Split String into Array with delimiter and limit
In this example, we are simply splitting the string using the space as a delimiter. Moreover, we are adding the limit as 3. Therefore, it will split the string using the space delimiter for 2 times.
// Program to split String into array using space delimiter and limit public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s="Welcome to the world of java programming "; // Using the split function String[] a = s.split(" ",3); // Printing the resultant array for (String i : a) System.out.println(i); >>
Welcome to the world of java programming
Example 3 : Split String into Array with another string as a delimiter
In this example, we are splitting the string using the another string as a delimiter. However, we are not adding any limit.
// Program to split String into array using other string as a delimiter public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey. Life is a Rose Garden."; String d = "Life is a "; // Using the split function String[] a = s.split(d); // Printing the resultant array for (String i: a) System.out.println(i); >>
Example 4 : Split String into Array with multiple delimiters
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array using multiple delimiters public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?"; // Using split function String[] a = s.split("[. ]"); // Printing the resultant array for (String i: a) System.out.println(i); >>
Life is a book Life is a Journey Is life is a Rose Garden
Example 5 : Split the String without using built-in split function
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array without using built-in split function public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Welcome to the world of java programming "; String[] a = new String[8]; int j = 0; a[0] = ""; // Iterating over string character by character for (int i = 0; i < s.length(); i++) < // If char is a space we increment the array index by 1 and store the next value as a next word if (s.charAt(i) == ' ') < j++; a[j] = ""; >else < a[j] = a[j] + s.charAt(i); >> // Printing the resultant array for (String i: a) System.out.println(i); > >
Welcome to the world of java programming
Example 6 : Split the content read from the file line wise
In this example, we are splitting the content of file line wise. So, the delimiter is a new line character( \n ). Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
The content of the text file is as shown below.
Test.txt Welcome to the world of Java Programming Its fun to learn Programming Have a good day!!
import java.io.*; public class Main < public static void main(String[] args) throws Exception < // Creating a file handle and bufferedreader object File file = new File("Test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st, fs = ""; // Reading from the file while ((st = br.readLine()) != null) fs = fs + st + "\n"; // Spliting into an array and printing String[] a = fs.split("\n"); for (String i: a) System.out.println(i); >>
Example 7 : Count the number of words in a string using split method
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array using multiple delimiters public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?"; // Using split function String[] a = s.split(" "); // Printing the resultant array for (String i: a) System.out.println(i); System.out.println("Total number of words in a string is " + a.length); >>
Life is a book. Life is a Journey! Is life is a Rose Garden? Total number of words in a string is 14
Summary
The knowledge of Splitting a string to an array in Java is very useful while working on real time applications. In this tutorial, we covered the way to split string into array using the built-in split function and without using split function. As per the requirement of an application, we can choose an appropriate approach for splitting. We learned in detail about splitting with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on splitting a string to an array in Java.
References
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Java Tutorial
- Set Up Java Environment
- Set Up Java on Linux
- Set up Java with BlueJ IDE
- Set up Java with VSC IDE
- Set up Java with Eclipse IDE
- Java Multiline Comments
- Java Variables
- Java Global Variables
- Java Date & Time Format
- Different Java Data Types
- Java Booleans
- Java Strings
- Java Array
- Java Byte
- Java convert list to map
- Java convert double to string
- Java convert String to Date
- Java convert Set to List
- Java convert char to int
- Java convert long to string
- Java Operators Introduction
- Java Boolean Operators
- Java Relational Operators
- Java Arithmetic Operators
- Java Bitwise Operators
- Java Unary Operators
- Java Logical Operators
- Java XOR (^) Operator
- Java Switch Statement
- Java If Else Statement
- Java While Loop
- Java For / For Each Loop
- Java Break Continue
- Java Nested Loops
- Java throw exception
- Java Try Catch
- Java Accessor and Mutator Methods
- Java main() Method
- IndexOf() Java Method
- Java ListIterator() Method
- Java create & write to file
- Java read file
- Java Parameter
- Java Argument
- Java Optional Parameters
- Java Arguments vs Parameters
- Java Arrays.asList
- Java HashSet
- Java Math
- Java HashMap vs Hashtable vs HashSet
- Java LinkedList
- Linked List Cycle
- Java List vs LinkedList
- Java ArrayList vs LinkedList
Java String split()
The String split() method returns an array of split strings after the method splits the given string around matches of a given regular expression containing the delimiters.
The regular expression must be a valid pattern and remember to escape special characters if necessary.
String str = "A-B-C-D"; String[] strArray = str.split("-"); // [A, B, C, D]
The split() method is overloaded and accepts the following parameters.
- regex – the delimiting regular expression.
- limit – controls the number of times the pattern is applied and therefore affects the length of the resulting array.
- If the limit is positive then the pattern will be applied at most limit – 1 times. The result array’s length will be no greater than limit, and the array’s last entry will contain all input beyond the last matched delimiter.
- If the limit is zero then result array can be of any size. The trailing empty strings will be discarded.
- If the limit is negative then result array can be of any size.
public String[] split(String regex); public String[] split(String regex, int limit);
1.2. Throws PatternSyntaxException
Watch out that split() throws PatternSyntaxException if the regular expression’s syntax is invalid. In the given example, “[” is an invalid regular expression.
String[] strArray = "hello world".split("[");
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
The method does not accept ‘null’ argument. It will throw NullPointerException in case the method argument is null.
Exception in thread "main" java.lang.NullPointerException at java.lang.String.split(String.java:2324) at com.StringExample.main(StringExample.java:11)
2. Java Programs to Split a String
2.1. Split with Specified Delimiter
The following Java program splits a string based on a given delimiter hyphen «-» .
String str = "how to do-in-java-provides-java-tutorials"; String[] strArray = str.split("-"); //[how to do, in, java, provides, java, tutorials]
The following Java program splits a string by space using the delimiter «\\s» . To split by all white space characters (spaces, tabs etc), use the delimiter “ \\s+ “.
String str = "how to do injava"; String[] strArray = str.split("\\s"); //[how, to, to, injava]
Java program to split a string by delimiter comma.
String str = "A,B,C,D"; String[] strArray = str.split(","); //[A,B,C,D]
2.4. Split by Multiple Delimiters
Java program to split a string with multiple delimiters. Use regex OR operator ‘|’ symbol between multiple delimiters.
In the given example, I am splitting the string with two delimiters, a hyphen and a dot.
String str = "how-to-do.in.java"; String[] strArray = str.split("-|\\."); //[how, to, do, in, java]
3. Split a String into Maximum N tokens
This version of the method also splits the string, but the maximum number of tokens can not exceed limit argument. After the method has found the number of tokens, the remaining unsplitted string is returned as the last token, even if it may contain the delimiters.
Below given is a Java program to split a string by space in such a way the maximum number of tokens can not exceed 5 .
String str = "how to do in java provides java tutorials"; String[] strArray = str.split("\\s", 5); System.out.println(strArray.length); //5 System.out.println(Arrays.toString(strArray)); //[how, to, do, in, java provides java tutorials]
This Java String tutorial taught us to use the syntax and usage of Spring.split() API, with easy-to-follow examples. We learned to split strings using different delimiters such as commas, hyphens, and even multiple delimiters in a String.