-3

I have a very long String. And I have a function write(String str) that can only support a string with 20 chars. How can I do to cut my long string into strings of 20 chars and loop in my write() function ?

Sorry, what I did :

for(String retval: pic.split("",20)) {
mBluetoothLeService.writeCharacteristic(characteristic, retval)

pic is my long String. however doing this, It's not doing what I want

Thank you in advance !

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
Bob
  • 111
  • 2
  • 9

2 Answers2

1

Use the susbtring() method:

with this you can have the 20 first characters:

pic = pic.substring(0, 21)
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
1

Here, using arraylist of Strings, and using substring, supports more than 20 chars

String pic = "THIS IS A VERY LONG STRING MORE THAN 20 CHARS";

ArrayList<String> strings = new ArrayList<String>();
int index = 0;

while (index < pic.length()) {
strings.add(pic.substring(index, Math.min(index + 20,pic.length())));
    index += 20; //split strings, add to arraylist
}

for(String s :strings){
    mBluetoothLeService.writeCharacteristic(characteristic, s); //write the string 
}

or, even better, using regex:

for(String s : pic.split("(?<=\\G.{20})"))
    mBluetoothLeService.writeCharacteristic(characteristic, s); 
EDToaster
  • 3,160
  • 3
  • 16
  • 25
  • Isn't pic.length() instead of text.length() ? Thanks for this usefull answer tho – Bob Feb 12 '15 at 00:51
  • I didn't really verified the code but you are sure that this actually makes strings of 20 chars right ? – Bob Feb 12 '15 at 01:00
  • @Bob Yup, an array of 20length strings, which you iterate through and call the method. – EDToaster Feb 12 '15 at 01:09
  • Well Actually I got this error : java.util.regex.PatternSyntaxException: Look-behind pattern matches must have a bounded maximum length near index 12: (?<=\G.{20}) , do you know why ? – Bob Feb 12 '15 at 01:18
  • Yes! it finally worked using the first answer! Regex bugs for me. Anyway thanks for the help ! :) – Bob Feb 12 '15 at 01:34