6

I want to split a string after a certain length.

Let's say we have a string of "message"

Who Framed Roger Rabbit 

Split like this :

"Who Framed" " Roger Rab" "bit"

And I want to split when the "message" variable is more 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 ..
}
newborn
  • 159
  • 1
  • 2
  • 12

4 Answers4

20

I wouldn't use String.split for 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()));
}

Addition 2018/5/8:

If you are simply printing the parts of the string, there is a more efficient option, in that it avoids creating the substrings explicitly:

PrintWriter w = new PrintWriter(System.out);
for (int i = 0; i < message.length(); i += 10) {
  w.write(message, i, Math.min(i + 10, message.length());
  w.write(System.lineSeparator());
}   
w.flush();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
4

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

"Who Framed Roger Rabbit ".split("(?<=\\G.{10})");
PeterK
  • 1,697
  • 10
  • 20
1

You could use a regex find, rather than a split something like this: [\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

This will work for you. Works for any length of message.

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
TheLostMind
  • 35,966
  • 12
  • 68
  • 104