-1

I want to split a text file that has all connected words "ABCDEFGHIJKLMNOPQRSTUVWXYZ" I want my output to print:

ABC
DEF
GHI
JKL 

I tried:

String text = StdIn.readAll();
String parts [] = text.split("\\s ",3);
for(String a: parts)
    System.out.println(a);
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 3
    Looks like a job for [`substring`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int,int)) rather then regex – Federico klez Culloca Apr 15 '21 at 21:41
  • https://stackoverflow.com/a/2297450/3792469 - relevant answers - `s.split("(?<=\\G...)"))` – Viv Apr 15 '21 at 21:48

3 Answers3

2

This answer should work, see this similar post Split string to equal length substrings in Java.

String[] parts = text.split("(?<=\\G.{3})");
Mady Daby
  • 1,271
  • 6
  • 18
  • Hiya, nice find, but for future - if you found an existing similar question with an answer, it is better to mark this question as duplicate rather than copy information over and over again from post to post :) – vs97 Apr 15 '21 at 21:47
  • Thankss! Please if you can explain what each part of this means ("(?<=\\G.{3})") – Nemanja M Apr 15 '21 at 21:48
  • @NemanjaM If you click on the link, another user has explained it there. – Mady Daby Apr 15 '21 at 21:52
1

Insert a separator with replaceAll, then split the string with split.

public static void main(String[] args) {

    String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    String parts[] = text.replaceAll("(.{3})", "$1,").split(",");
    
    for (String a : parts)
        System.out.println(a);
}

Result:

ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
Stéphane Millien
  • 3,238
  • 22
  • 36
1

.substring() solution:

String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(int i= 0; i < text.length(); i+=3)
  System.out.println((i+3 <= text.length() ? text.substring(i, i+3) : text.substring(i)));

Result:

ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
Spectric
  • 30,714
  • 6
  • 20
  • 43