问题描述
我对Java还是很陌生,并且遇到了一个特殊的家庭作业问题,即一个字符串通过传递,然后我必须将其拆分成与传递的整数相等的部分.
I'm fairly new to Java and am stuck on a particular homework question where a String gets passes and from there I have to split it into parts equal to an Integer that was passed.
例如:输入字符串"HelloWorld",必须将其除以2,然后将这些部分放入具有以下两个部分的数组中:array [hello,world].
For example: String "HelloWorld" is input and it has to be divided by 2 and those parts then have to be put into an array that has two parts like: array[hello, world].
是否有使用FOR循环执行此操作的方法?
Is there anyway to do this using a FOR loop?
到目前为止,我的代码将整个String输入每个数组元素.这是我的代码:
My code so far enters the whole String into each array element. Here is my code:
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;
}
推荐答案
我知道了.这是我的代码:
I figured it out. Here is my code:
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;
这篇关于如何将字符串分成相等的部分并将其存储在字符串数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!