【问题标题】:How to delimit a string to a string with certain length with Java?java - 如何使用Java将字符串分隔为具有一定长度的字符串?
【发布时间】:2015-02-12 00:32:20
【问题描述】:

我有一个很长的字符串。我有一个函数 write(String str) 只能支持 20 个字符的字符串。如何将我的长字符串切割成 20 个字符的字符串并在我的 write() 函数中循环?

对不起,我做了什么:

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

pic 是我的长字符串。但是这样做,它没有做我想要的

提前谢谢你!

【问题讨论】:

标签: java arrays string split char


【解决方案1】:

这里使用String的arraylist,使用substring,支持20多个字符

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 
}

或者,更好的是,使用正则表达式:

for(String s : pic.split("(?<=\\G.{20})"))
    mBluetoothLeService.writeCharacteristic(characteristic, s); 

【讨论】:

  • 不是 pic.length() 代替 text.length() 吗?感谢您提供这个有用的答案
  • 我并没有真正验证代码,但你确定这实际上是 20 个字符的字符串吗?
  • @Bob Yup,一个 20 长度的字符串数组,您可以遍历并调用该方法。
  • 其实我得到了这个错误:java.util.regex.PatternSyntaxException: Look-behind pattern match must have a bounded maximum length near index 12: (?
  • 是的!它终于使用第一个答案起作用了!对我来说正则表达式错误。无论如何感谢您的帮助! :)
【解决方案2】:

使用susbtring() 方法:

这样你就可以拥有前 20 个字符:

pic = pic.substring(0, 21)

【讨论】:

  • OP 声明他们想要超过 20 个字符:P 这意味着你将不得不循环
  • “只能支持20个字符的字符串”。
  • 他的意思是 mBluetoothLeService.writeCharacteristic 只能支持 20 个字符,因此,我引用,需要“在我的 write() 函数中循环”
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 2012-09-04
  • 2020-08-14
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多