我对Java还是很陌生,并且遇到了一个特殊的家庭作业问题,在该问题中,字符串得到了传递,然后我必须将其拆分成与传递的整数相等的部分。
例如:输入字符串“ HelloWorld”,必须将其除以2,然后将这些部分放入具有两个部分的数组中,例如:array [hello,world]。
反正有使用FOR循环来做到这一点吗?
到目前为止,我的代码将整个String输入每个数组元素。这是我的代码:
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;
}
我想到了。这是我的代码:
String[] array = new String[size];
char[] charArray = new char[length(word)];
char[] temp = new char[length(word) / size];
int place = 0;
// turn the string into an array of chars
for (int i = 0; i < charArray.length; i++) {
charArray[i] = getChar(word, i);
}
// loop for each element of the desired string array
for (int i = 0; i < array.length; i++) {
// fill a temp array with the correct characters and the corect amount of characters
for (int j = 0; j < charArray.length / size; j++) {
temp[j] = charArray[place];
++place;
}
// insert the temp array into each element of the string array
array[i] = new String(temp);
}
return array;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句