![](/img/trans.png)
[英]BufferedReader saving sentence, String array, then 2D int array
[英]Sentence/string to 2D array in java
我需要从给定的字符串制作一个二维数组。 行数将是字符串中的单词数,列数将是字符串中最长单词的长度(单词用空格分隔)。 如果在字符串中有一个 2 个字母的单词(例如“是”)并且列号为 8,我需要用空格填充其余的单元格。
例子:
字符串:“aaa bbbb ccccc dddddd”
数组:stringArray[4][6]
输出:{{a,a,a,' ',' ',' '},{b,b,b,b,' ',' '},{c,c,c,c,c,' '} ,{d,d,d,d,d,d}}
代码是:
public static void TextToArray(String s) {
int rowCount = 0;
int columnCount = 0;
int tempColumn = 0;
//getting array dimensions and creating an array
for (int i = 0; i < s.length(); i++) {
tempColumn++;
if (s.charAt(i) == ' ') {
rowCount++;
if (tempColumn > columnCount) {
columnCount = tempColumn;
}
tempColumn = 0;
}
}
char[][] stringArray = new char[rowCount + 1][tempColumn];
//filling array - not completed
for (int i = 0; i < stringArray.length ; i++) {
for (int j = 0; j < stringArray[i].length ; j++) {
if(s.charAt(j) == ' '){
for (int k = j; k < stringArray[i].length - j ; k++) {
stringArray[i][j] = ' ';
}
}
stringArray[i][j] = s.charAt(j);
System.out.print(stringArray[i][j] + ", ");
}
System.out.println();
}
我在向空单元格插入空格时遇到问题(我不知道 - 我需要一些指针来实现)。 我还停留在 j 循环结束并从开头开始的地方(循环插入数组的字母从字符串的开头开始 - 我不知道在哪里插入条件以继续遍历字符串长度)。 我知道方法的第二部分很糟糕,但我需要帮助来结束它。
首先,您将字符串按空格分隔为分隔符,这样您就可以得到行数。 然后您搜索最长的子字符串以获得您的列数。 之后,您可以按行插入它们,其中第 n 行等于您在 tmp 数组中的第 n 个位置。 if 语句用“ ”填充单词后面的每个单元格(如果单词不是输入字符串中最长的)。
public static void TextToArray(String s) {
String[] tmp = s.split(" ");
int rowCount = tmp.length;
int columnCount = 0;
for(int i = 0;i < tmp.length; i++) {
if(tmp[i].length() > columnCount) {
columnCount = tmp[i].length();
}
}
char[][] charArray = new char[rowCount][columnCount];
for(int j = 0; j < rowCount; j ++) {
for(int k = 0;k<columnCount;k++) {
if(k<tmp[j].length()) {
charArray[j][k] = tmp[j].charAt(k);
}
else {
charArray[j][k] = ' ';
}
}
}
}
让我向您建议一个类似的算法,在第一步使用列表而不是字符串数组来操作一点点函数式编程
public class Main {
public static void main(String[] args) {
String s = "aaa bbbb ccccc dddddd";
char[][] stringArray = text2array(s);
for (int i = 0; i < stringArray.length ; i++)
for (int j = 0; j < stringArray[i].length ; j++)
System.out.print(stringArray[i][j]);
}
public static char[][] text2array (String st) {
List<String> list = Arrays.asList(st.split(" "));
Optional<String> wordMax = list.stream().reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2);
int maxLength = 0;
if(wordMax.isPresent()) {
maxLength = wordMax.get().length();
}
char[][] array = new char[list.size()][maxLength];
for (int line = 0; line < list.size(); line++) {
for (int col = 0; col < maxLength; col++) {
String word = list.get(line);
if (col < word.length()) array[line][col] = word.charAt(col);
else array[line][col] = ' ';
};
}
return array;
}
}
output : aaa bbbb ccccc dddddd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.