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 ..
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With