簡體   English   中英

在Java中拆分或解析字符串

[英]Split or parse a string in java

我有一個sample.txt文件,其內容為

12345#ABCDEF#12345#ADCDE

12345#ABCDEF#12345#ADCDE

FHJI

KLMN

OPQ

12345#ABCDEF#12345#ADCDE

現在我想基於#來分割/解析文件

我的輸出應該是

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

        FHJI

        KLMN

        OPQ

Test1 : 12345

Test2 : ABCDEF

Test3 : 12345

Test4 : ADCDE

我寫如下

String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {
    String line[] = sCurrentLine.split("#");
    Test1 = line[0];
    Test2 = line[1];
    Test3 = line[2]
    Test4 = line[3];
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
    }

如果只有一行或sample.txt如下所示,則表示它正在工作

12345#ABCDEF#12345#ADCDE

12345#ABCDEF#12345#ADCDE

它不適用於已聲明的最高示例。

請幫我。

謝謝。

這條線

String line[] = sCurrentLine.split("#");

將字符串拆分為n片段,如果您解析的行中不存在# ,則會崩潰。 為了解決此問題,您有2個選擇:

  • 修復文件
  • 分配前檢查數組的長度,以避免AIOOBE

     while ((sCurrentLine = br.readLine()) != null) { String line[] = sCurrentLine.split("#"); Test1 = line[0]; Test2 = line.lenght > 1 ? line[1] : ""; Test2 = line.lenght > 2 ? line[2] : ""; Test2 = line.lenght > 3 ? line[3] : ""; System.out.println(Test1+"\\n"+Test2+"\\n"+Test3+"\\n"+Test4); } 

您必須檢查是否可以將字符串分割成所需的部分數量

String sCurrentLine;
String Test1 = "";
String Test2= "";
String Test3= "";
String Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {
    String line[] = sCurrentLine.split("#");
    if (line.length >= 4) {
        Test1 = line[0];
        Test2 = line[1];
        Test3 = line[2]
        Test4 = line[3];
    } else {
         Test4 = line[0] + "\n";
    }
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}

做這樣的事情,以檢查字符串中是否有足夠的段。

String sCurrentLine;
String Test1, Test2, Test3, Test4 = "";

br = new BufferedReader(new FileReader("D:\\sample.txt"));

while ((sCurrentLine = br.readLine()) != null) {

  String line[] = sCurrentLine.split("#");
  if(line.length >= 4){
    Test1 = line[0];
    Test2 = line[1];
    Test3 = line[2]
    Test4 = line[3];
  }
    System.out.println(Test1+"\n"+Test2+"\n"+Test3+"\n"+Test4);
}

暫無
暫無

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

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