[英]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.