How to use line splitting after a certain length?

I want to split a string after a certain length.

Say we have the string "message"

Who Framed Roger Rabbit 

Divide like this:

"Who Framed" " Roger Rab" "bit"

And I want to split when the variable "message" is greater than 10.

my current split code:

private void sendMessage(String message){

// some other code ..

String dtype = "D";
int length = message.length();
String[] result = message.split("(?>10)");
for (int x=0; x < result.length; x++)
        {
            System.out.println(dtype + "-" + length + "-" + result[x]); // this will also display the strd string
        }
// some other code ..
}
+4
source share
4 answers

I would not use String.splitfor this at all:

String message = "Who Framed Roger Rabbit";
for (int i = 0; i < message.length(); i += 10) {
  System.out.println(message.substring(i, Math.min(i + 10, message.length());
}
+15
source

I think Andy's solution would be the best in this case, but if you want to use regex and split, you could do

"Who Framed Roger Rabbit ".split("(?<=\\G.{10})");
+3
source

. .

public static void main(String[] args) {
    String message =  "Who Framed Roger Rab bit";
    if (message.length() > 10) {
        Pattern p = Pattern.compile(".{10}|.{1,}$");
        Matcher m = p.matcher(message);
        while (m.find()) {
            System.out.println(m.group());
        }   
    }
}

O/P:

Who Framed
 Roger Rab
 bit
0

, - : [\w ]{0,10}

Pattern p = Pattern.compile("[\\w ]{0,10}");
Matcher m = p.matcher("who framed roger rabbit");
while (m.find()) {
    System.out.println(m.group());
}
0
source

Source: https://habr.com/ru/post/1615790/


All Articles