我想将字符串转换为2D数组。 但是我的问题是字符串应该是动态的。 结果也应该是动态的。我尝试使用队列,但无法提出解决方案。
sentence =“这是一个例子。” 2DArray [] [] = convertInto2dArray(sentence)
2D阵列应如下所示。 [[T] [h] [i] [s],[i] [s],[a] [n],[e] [x] [a] [m] [p] [l] [e], [。]]
答案 0 :(得分:0)
在Java中,多维数组不过是数组的数组,因此使用两个多维数组[[T][h][i][s],[i][s],[a][n],[e][x][a][m][p][l][e],[.]]
是不可能的。您应该有3个三维阵列。
签出:https://www.baeldung.com/java-jagged-arrays
希望这可以达到您的目的:
static char[][][] convert(String text) {
String[] strSplit = text.split(" ");
char[][][] out = new char[strSplit.length][][];
for (int i = 0; i < strSplit.length; i++) {
char[] word = strSplit[i].toCharArray();
char[][] inner = new char[word.length][];
for (int j = 0; j < word.length; j++) {
inner[j] = new char[] { word[j] };
}
out[i] = inner;
}
return out;
}
输出:
[[[T], [h], [i], [s]], [[i], [s]], [[a], [n]], [[e], [x], [a], [m], [p], [l], [e], [.]]]
答案 1 :(得分:0)
我想像这样:
def stringToArray(newstring):
words = wordsandpoints(newstring)
char newarray[wordsandpoints][]
i=0
row = 0
for(;row < words;):
for(int column=0;column < newstring.length(); column++, i++):
if(newstring[i] =! " " or newstring[i] != ".")
newarray[row][column] = newstring[i]
elif(newstring[i] == ".")
row++
newarray[row][column] = newstring[i]
row++
else
row++
return newarray
def wordsandpoints(b):
i = 0
for x in b:
if(x == " ")
i++
elif(x == ".")
i = i + 2
return i