Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use split a string after a certain length? [duplicate]

Tags:

java

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 ..
}
like image 678
newborn Avatar asked Nov 13 '15 15:11

newborn


1 Answers

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();
like image 161
Andy Turner Avatar answered Oct 13 '22 01:10

Andy Turner