- Java String split()
- Split with delimiters java
- Split with delimiters java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Split with delimiters java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
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.
Split with delimiters 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. Больше подробностей — в нашем Пользовательском соглашении.
Split with delimiters java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter
Split with delimiters java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter