我正在寻找一个解决方案,将split
一个字符串,并返回包含相等数量的字符的值。我尝试了String类的所有流行方法,但未获得所需的输出。
谁能帮我找到如何在Java中拆分字符串,以给出数量相等的大小n的值。
输入样例:
字串= JavaProgrammingIsAwesome
范围= 5
所需输出:
JavaP,
rogra,
mming,
IsAwe,
some
您可以通过一些计算和使用String#substring
方法执行相同的操作:
public static List<String> splitWithinRange(String str, int size) {
// Take the String
// Make an ArrayList object (with calculated size)
List<String> theList = new ArrayList<String>((str.length() + size - 1) / size);
// Increment the k with respect to given range or size
for (int k = 0; k < str.length(); k += size) {
// Split the substrings and add into the List
theList.add(
str.substring(k , Math.min(str.length(), k + size))
);
}
// Return the List
return theList;
}
上述解决方案将针对给定范围在Java中拆分字符串。
基于String#split()
和Regex
的解决方案也可能对您有用,但是要小心,因为Regex
它具有不同的风格,并且可能不适用于所有地方。
但是,该split()
方法也可以帮助实现它-
希望,这就是您想要做的!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句