Java将单个字符从char数组转换为String数组

时间:2018-02-26 19:15:52

标签: java arrays

我正在从文本文件中读取一个单词(程序),我想将其存储到名为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
   }

3 个答案:

答案 0 :(得分:1)

String(char)中未定义String构造函数。所以你做不到:

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]); 

答案 1 :(得分:1)

要在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

答案 2 :(得分:0)

String text = String.copyValueOf(data);

String text = String.valueOf(data);

更好 - 封装新的String调用