Split java string by length
если не хотите экранировать или не знаете, надо ли, просто пишите 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 String By Length in Java
An example on splitting a string after ‘n’ characters i.e. into chunks with n characters each in Java.
Let’s Split
import java.util.*;
class SplitByLength
public static void main(String args[])
// Create a Scanner object for taking input from cmd
Scanner s=new Scanner(System.in);
// Read a line from the user, space is not ignored
String st=s.nextLine();
// Take the split length
int len=s.nextInt();
// No.of possible strings for that length
int k=(st.length()/len);
// Print it if you wish to
System.out.println(k);
// Initialize the variable m=0, m acts as cursor
int m=0;
// Loop no.of possible string times [See analysis]
for(int i=0;i <(k+1);i++)
// Increase m value if i is not equal to 0 or greater than 0
if(i!=0) m=m+len;
// If length of string is greater or = to cursor position+split length, then..
if(st.length()>=m+len)
// Print the part of the string b/w cursor position and split length number of chars after cursor position
System.out.println((st.substring(m,m+len)));
>
// If length of string is less than cursor position + split length,then..
else if(st.length()
// Print the string from cursor position till end
System.out.println((st.substring(m,st.length())));
>
>
>
>
Analysis
Why nextLine(): Because it does not ignore space, try using s.next() instead of s.nextLine() and run the program, you’ll have a clear understand about the difference.
int k=st.length()/len: The no.of possible chunks with equal size. For example, consider gowthamgutha as the string that is to be split and the maximum size of each chunk be 2 (len=2), then the possible chunks are
And if we consider gowtham gutha whose length is an odd number (here 13) and the maximum size of each chunk be 2,then
Here, the no.of chunks are 7 and the last chunk size is just 1. If you can observe, the length of the string is an odd number and therefore we’ve got odd number of chunks.
m=0: m acts as cursor, it moves in accordance with the chunk i.e. if the size of the chunk is 2, initially it will be at starting of the string and later it jumps to 2 (0+2) and from 2 to 4 (2+2) and from 4 to 6 (4+2) and so on till the end of the string. All this happens when the length of the string is greater than the size of the chunk. If not, then the cursor will not move, it will be at 0 only and the chunk is the string only, so the string will be printed from 0 till the end.
if(i!=0) m=m+len: You’ll have to split the string from starting. The initial value of m is 0 and it should not update for the first time, because if you can see the statement below, st.substring(m,m+len) for the first time, it has to be substring(0,0+len) for example, if len=2, then
substring(0,0+2)
So, the string has to split from starting (from index 0), that’s why.
st.length()>m+len: If the length of the string is greater than the length of the sum of the cursor position and length of the string, then..
st.substring(m,m+len): Pick the part of the string between cursor position and the next cursor position. The next cursor position will be nothing but the sum of the current cursor position (current index) and the given length of the chunk.