簡體   English   中英

Java將單個字符從char數組轉換為String數組

[英]Java convert individual characters from char array to String array

我正在從文本文件中讀取一個單詞(程序),我想將其存儲到名為word1二維數組中。 為此,我讀取文件並將其存儲到占位符數組中。 然后,我將此占位符數組轉換為char數組,以便將每個字母拆分。 現在,我想將這個char數組中的單個字母發送回我先前創建的字符串數組( word1 )。 最終,我希望word1數組變成這樣

String word1[][] = {
   {"p", "*"}, {"r", "*"}, {"o", "*"}, {"g", "*"}, {"r", "*"}, {"a", "*"}, {"m", "*"},
};

一切工作直到最后一位嘗試將char數組中的各個字母轉換回word1數組為止。

FileReader file = new FileReader("C:/Users/Mark/Desktop/Java/Workshop 2/hangman.txt");
BufferedReader reader = new BufferedReader(file);

String text = "";
String line = reader.readLine(); //Keeps reading line after line 
while (line != null){
  text += line;
  line = reader.readLine();
}

String word1[][] = {
  {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"}, {"", "*"},
};

String placeholder[] = text.split("\\s+");   //Converts text into an array

String s = "";
   for (String n:placeholder){
    s+= n;
  }

char[] charArray = s.toCharArray();

   for (int i = 0; i < 6; i++){
     word1[i][0] = new String(charArray[i]); //This is where problem occurs
   }

沒有在String定義String(char)構造函數。 所以你不能做:

String word1[][]  = ...;
word1[i][0] = new String(charArray[i]); //This is where problem occurs

您需要的是String.valueOf(char c)

word1[i][0] = String.valueOf(charArray[i]); 

要在Stringchar[][]之間來回轉換,請使用以下方法:

public static char[][] toCharArray(String text) {
    char[][] c = new char[text.length()][2];
    for (int i = 0; i < c.length; i++) {
        c[i][0] = text.charAt(i);
        c[i][1] = '*';
    }
    return c;
}

public static String toString(char[][] c) {
    char[] buf = new char[c.length];
    for (int i = 0; i < c.length; i++)
        buf[i] = c[i][0];
    return new String(buf);
}

測試

char[][] word1 = toCharArray("program");
System.out.println(Arrays.deepToString(word1));

String text = toString(word1);
System.out.println(text);

輸出量

[[p, *], [r, *], [o, *], [g, *], [r, *], [a, *], [m, *]]
program

哦對不起,這應該是String到/從String[][]

public static String[][] toArray2D(String text) {
    String[][] arr = new String[text.length()][];
    for (int i = 0; i < arr.length; i++)
        arr[i] = new String[] { text.substring(i, i + 1), "*" };
    return arr;
}

public static String toString(String[][] arr) {
    StringBuilder buf = new StringBuilder();
    for (String[] a : arr)
        buf.append(a[0]);
    return buf.toString();
}

測試

String[][] word1 = toArray2D("program");
System.out.println(Arrays.deepToString(word1));

String text = toString(word1);
System.out.println(text);

輸出量

[[p, *], [r, *], [o, *], [g, *], [r, *], [a, *], [m, *]]
program

字符串文本= String.copyValueOf(data);

要么

字符串文本= String.valueOf(data);

更好-封裝新的String調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM