阅读的文本字符串转换成二维数组 [英] Read text string into 2D array

查看:199
本文介绍了阅读的文本字符串转换成二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要读一组文本字符串的文件到一个二维数组。文本字符串格式看起来像这样,每一行用\\ N与各种长度

结束

 狗,奔跑,快
    鸟,苍蝇,高
    宝贝,呐喊,经常,晚上
    他,作品
    ....

想获得下面的二维数组输出:

  {{狗,奔跑,快},{鸟,苍蝇,高},
    {宝贝,呐喊,经常,晚上},{他,作品},
     ...
  }

思考使用StringBuilder的从文件中读取每一行并将其追加到2D对象[] []数组(但使用的String [] []代替)。下面codeS是我最初的attemps - 不是pretty,但不工作或者

 进口java.io. *;
                   进口的java.util。*;                  公共类My2DArrayTest
                          {
                  公共静态无效的主要(字符串ARGS [])
                           {                的String [] [] =的myString新的String [4] [3];                        尝试
                               {
                        的FileReader文件=新的FileReader(MyTestFile.txt);
                        读者的BufferedReader =新的BufferedReader(文件);
                         串strLine中;
                          串EXAMPLE_TEST;
                           对(INT行= 0;行4;;排++){
                      对(INT列= 0;柱3;;柱++){
                            而((strLine中= reader.readLine())!= NULL {                        如果(strLine.length()大于0){
                      EXAMPLE_TEST = strLine中;
                           的System.out.println(这是EXAMPLE_TEST:+
                                     EXAMPLE_TEST);
               MyString的[行] [列] = EXAMPLE_TEST;
               的System.out.println(当前行:+行);
               的System.out.println(当前栏目:+列);
               的System.out.println(这是MyString的数组:+
                                    MyString的[行] [列] +);
                }
                  }
                                     }
                                                              }
                               file.close();                   }赶上(IOException异常IOException异常){}
                                 }
                                      }


解决方案

首先,你必须决定如何处理的事实,你不知道在启动时的行数。你可以:


    先进入
  1. 计数线,从而创建所需大小的结果数组,然后再阅读您的文件和填充阵列的数据。

  2. 店铺一列表代替。
  3. 里面的台词

(我会选择2)其次,你想要什么字符,可以让你的字符串里面呢?例如 \\ n (行)可以使事情更加复杂,因为你将不得不逃离他们,但我们假设这些字符将被禁止(和,这样我们就可以更容易地分割)

在=新扫描仪

 扫描仪(新文件(strings.test));
清单<的String []>行=新的ArrayList<>();
而(in.hasNextLine()){
    。串线= in.nextLine()修剪();
    串[]分裂= line.split(,);
    的for(int i = 0; I< splitted.length;我++){
        //在开始和结束摆脱额外的
        分裂[I] =分裂[I] .substring(1,分裂[I]。长度() - 1);
    }
    lines.add(分裂);
}// pretty多少事,现在转换列表<的String []>为String [] []
的String [] []结果=新的String [lines.size()] [];
的for(int i = 0; I< result.length;我++){
    结果由[i] = lines.get(ⅰ);
}的System.out.println(Arrays.deepToString(结果));

输出:

  [狗,跑,快],[鸟,蝇,高],[婴儿哭声,经常在晚上],[他,作品]

如果您需要任何这些characted我扔掉的,让我知道在评论,我会编辑这个答案。

Need to read a set of text string files into a 2D array. The text string format looks like this, each line ends with "\n" with various length

    "dog", "runs", "fast"
    "birds", "flies", "high"
    "baby", "cries", "often", "in the evening"
    "He", "works"
    ....

Would like to get the 2D array output below:

  { {"dog", "runs", "fast"}, {"birds", "flies", "high"}, 
    {"baby", "cries", "often", "in the evening"}, {"He", "works"}, 
     ...
  }

Thinking to use StringBuilder to read each line from a file and append it to a 2D Object [][] array (but used String [][] instead). The following codes are my initial attemps - not pretty, but not working either.

                   import java.io.*;
                   import java.util.*;

                  public class My2DArrayTest
                          {
                  public static void main(String args[])
                           {

                String[][] myString = new String[4][3];

                        try
                               {
                        FileReader file = new FileReader("MyTestFile.txt");
                        BufferedReader reader = new BufferedReader (file);
                         String strLine;
                          String EXAMPLE_TEST;  
                           for (int row = 0;  row < 4;  row++) {
                      for (int column = 0;  column < 3;  column++) {
                            while ((strLine = reader.readLine()) != null{

                        if (strLine.length() > 0) {
                      EXAMPLE_TEST = strLine;
                           System.out.println ("This is EXAMPLE_TEST: " +   
                                     EXAMPLE_TEST);


               myString[row][column]=EXAMPLE_TEST;
               System.out.println("Current row: " + row);
               System.out.println("Current column: " + column);
               System.out.println("This is myString Array:" + 
                                    myString[row][column] + " ");
                }
                  }  
                                     }
                                                              }
                               file.close();

                   }   catch( IOException ioException ) {}
                                 }
                                      }

解决方案

First of all, you will have to decide how to handle the fact that you don't know the number of lines at start. You could:

  1. Count lines in first go to create result array of desired size, then read your file again and fill that array with data.
  2. Store your lines inside a List instead.

(i will choose 2) Second, what characters you want to allow inside your strings? for example " or \n (newline) can make things more complicated since you would have to escape them, but let's assume that these characters will be banned (and also ,, so we can split more easily)

Scanner in = new Scanner(new File("strings.test"));
List<String[]> lines = new ArrayList<>();
while(in.hasNextLine()) {
    String line = in.nextLine().trim();
    String[] splitted = line.split(", ");
    for(int i = 0; i<splitted.length; i++) {
        //get rid of additional " at start and end
        splitted[i] = splitted[i].substring(1, splitted[i].length()-1);
    }
    lines.add(splitted);
}

//pretty much done, now convert List<String[]> to String[][]
String[][] result = new String[lines.size()][];
for(int i = 0; i<result.length; i++) {
    result[i] = lines.get(i);
}

System.out.println(Arrays.deepToString(result));

Output:

[[dog, runs, fast], [birds, flies, high], [baby, cries, often, in the evening], [He, works]]

If you need any of those characted that i "threw away", let me know in comment and i'll edit this answer.

这篇关于阅读的文本字符串转换成二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆