我是 Java 的新手,一直被困在一个特定的家庭作业问题上,在这个问题上,一个字符串通过了,我必须从那里将它分成与通过的整数相等的部分。
例如:输入字符串“HelloWorld”,它必须除以 2,然后必须将这些部分放入一个包含两部分的数组中,例如:array[hello, world]。
有没有办法使用 FOR 循环来做到这一点?
到目前为止,我的代码将整个字符串输入到每个数组元素中。这是我的代码:
String[] splitIntoParts(String word, int size) {
String[] array = new String[size];
for (int i = 0; i < array.length; i++) {
array[i] = word;
println(array[i]);;
}
return array;
}
最佳答案
有很多种方法:
这是正则表达式版本:
public void splitEqual(String s){
int length = s.length();//Get string length
int whereToSplit;//store where will split
if(length%2==0) whereToSplit = length/2;//if length number is pair then it'll split equal
else whereToSplit = (length+1)/2;//else the first value will have one char more than the other
System.out.println(Arrays.toString(s.split("(?<=\\G.{"+whereToSplit+"})")));//split the string
}
\G
是一个零宽度断言,它匹配上一个匹配结束的位置。如果没有先前的匹配项,它将匹配输入的开头,与 \A 相同。
封闭的后视匹配从上一个匹配项的末尾起四个字符的位置。
lookbehind 和\G 都是高级正则表达式功能,并非所有版本都支持。此外,\G
并没有在支持它的风格中一致地实现。这个技巧(例如)在 Java、Perl、.NET 和 JGSoft 中有效,但在 PHP (PCRE)、Ruby 1.9+ 或 TextMate(两者都是 Oniguruma)中无效。
使用子串:
/**
* Split String using substring, you'll have to tell where to split
* @param src String to split
* @param len where to split
* @return
*/
public static String[] split(String src, int len) {
String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
for (int i=0; i<result.length; i++)
result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
return result;
}
您还应该检查这个答案:Google Guava split
关于java - 如何将字符串拆分为相等的部分并将其存储在字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114025/