我想根据子字符串的长度将字符串转换为子字符串数组。有没有不使用循环的解决方案? 例如:
"this is a test" -> ["thi","s i","s a"," te","st"]
<小时/>
更新:
最佳答案
System.out.println(java.util.Arrays.toString("this is a test".split("(?<=\\G...)")));
句点“.”的数量表示每个子字符串有多少个字符。
<小时/>编辑
正如 Mick Mnemonic 指出的,您还可以使用 Kevin Bourrillion's example :
Java does not provide very full-featured splitting utilities, so the Guava libraries do:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
Check out the Javadoc for Splitter; it's very powerful.
如果你不想使用正则表达式,并且不希望依赖第三方库,你可以使用这个方法来代替,它需要介于 2.80 GHz CPU 中的 89920 和 100113 纳秒(小于一毫秒):
/**
* Divides the given string into substrings each consisting of the provided
* length(s).
*
* @param string
* the string to split.
* @param defaultLength
* the default length used for any extra substrings. If set to
* <code>0</code>, the last substring will start at the sum of
* <code>lengths</code> and end at the end of <code>string</code>.
* @param lengths
* the lengths of each substring in order. If any substring is not
* provided a length, it will use <code>defaultLength</code>.
* @return the array of strings computed by splitting this string into the given
* substring lengths.
*/
public static String[] divideString(String string, int defaultLength, int... lengths) {
java.util.ArrayList<String> parts = new java.util.ArrayList<String>();
if (lengths.length == 0) {
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
while (string.length() > 0) {
if (string.length() < defaultLength) {
parts.add(string);
break;
}
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
}
} else {
for (int i = 0, temp; i < lengths.length; i++) {
temp = lengths[i];
if (string.length() < temp) {
parts.add(string);
break;
}
parts.add(string.substring(0, temp));
string = string.substring(temp);
}
while (string.length() > 0) {
if (string.length() < defaultLength || defaultLength <= 0) {
parts.add(string);
break;
}
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
}
}
return parts.toArray(new String[parts.size()]);
}
关于java - java中如何根据子字符串的长度将字符串转换为子字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549990/