如何将字符串转换为2d char数组

时间:2014-03-15 02:50:26

标签: java arrays chars

我有一个像这样的文本文件

A B C D E F
AABG EF 123
AD AD POLFE
APF PLF ADS

我正在尝试将包含空格的每个字符放入2D数组中;

我试过这个

data = new ASCIIDataFile();
int rowLen =0;
String s = "";
while(data.isEOF()!=true){
    iArray[rowLen] = data.readLine().toCharArray();
    rowLen++;
    }

但这会给我一个空指针。我如何将它们放在二维char数组中?

3 个答案:

答案 0 :(得分:1)

这可以按照您的意愿。它将您的输出拆分为字符串数组,然后为每个数组创建一个新的char数组。

   import  java.util.Arrays;
/**
   <P>{@code java SplitStringsTo2DCharArray}</P>
 **/
public class SplitStringsTo2DCharArray  {
   private static final String LINE_SEP = System.getProperty("line.separator", "\r\n");
   public static final void main(String[] ignored)  {
      StringBuilder input = new StringBuilder().
         append("A B C D E F").append(LINE_SEP).
         append("AABG EF 123").append(LINE_SEP).
         append("AD AD POLFE").append(LINE_SEP).
         append("APF PLF ADS").append(LINE_SEP);

      String[] lines = input.toString().split(LINE_SEP);

      //Assumes all lines are the same length
      char[][] charCharArray = new char[lines.length][lines[0].length()];

      for(int i = 0; i < lines.length; i++)  {
         String line = lines[i];
         charCharArray[i] = line.toCharArray();
      }

      for(int i = 0; i < charCharArray.length; i++)  {
         System.out.println(i + ": " + Arrays.toString(charCharArray[i]));
      }
   }
}

输出:

[C:\java_code\]java SplitStringsTo2DCharArray
0: [A,  , B,  , C,  , D,  , E,  , F]
1: [A, A, B, G,  , E, F,  , 1, 2, 3]
2: [A, D,  , A, D,  , P, O, L, F, E]
3: [A, P, F,  , P, L, F,  , A, D, S]

答案 1 :(得分:0)

来自文件的char数组。

 File path = new File("c:/Bala/");//give ur path
      File file = new File(path, "Bala.txt");//give ur filename
      FileReader fr = new FileReader(file);
      char cbuf[] = new char[(int) file.length()];
      fr.read(cbuf);
      System.out.println(cbuf);

答案 2 :(得分:0)

    Try This demo:

   import java.io.*;
   import java.util.*;
    class d
    {
    public static void main(String args[])
   {
        try
            {
         FileReader fr = new FileReader("String.txt");
         BufferedReader br = new BufferedReader(fr);
         String s="";
         char [] r2;
         int i=0,j=0;
         char [][]c=new char[5][12];
         while((s = br.readLine()) != null) 
         {
         r2=s.toCharArray();

         for(j=0;j<r2.length;j++)
         {
          c[i][j]=r2[j];
          System.out.print(""+c[i][j]);
          System.out.print(",");
        }
        i++;
        System.out.print("\n");
            }
        }
       catch(Exception e)
        {
         e.printStackTrace();
         }
       }
    }

enter image description here