簡體   English   中英

從文本文件一次向數組列表中添加 3 個字符的最有效方法是什么?

[英]What is the most efficient way to add 3 characters at a time to an araylist from a text file?

假設您有一個帶有“abcdefghijklmnop”的文本文件,並且您必須一次向字符串類型的數組列表中添加 3 個字符。 因此,數組列表的第一個單元格將具有“abc”,第二個單元格將具有“def”,依此類推,直到輸入所有字符。

 public ArrayList<String> returnArray()throws FileNotFoundException
 {
    int i = 0
    private ArrayList<String> list = new ArrayList<String>();

    Scanner scanCharacters = new Scanner(file);

    while (scanCharacters.hasNext())
    {
        list.add(scanCharacters.next().substring(i,i+3);
        i+= 3;
    }

    scanCharacters.close();

    return characters;
}

請使用以下代碼,

ArrayList<String> list = new ArrayList<String>();
    int i = 0;
    int x = 0;
    Scanner scanCharacters = new Scanner(file);
    scanCharacters.useDelimiter(System.getProperty("line.separator"));
    String finalString = "";
    while (scanCharacters.hasNext()) {
        String[] tokens = scanCharacters.next().split("\t");
        for (String str : tokens) {
            finalString = StringUtils.deleteWhitespace(str);
            for (i = 0; i < finalString.length(); i = i + 3) {
                x = i + 3;
                if (x < finalString.length()) {
                    list.add(finalString.substring(i, i + 3));
                } else {
                    list.add(finalString.substring(i, finalString.length()));
                }
            }
        }


    }


    System.out.println("list" + list);

在這里,我使用了 Apache String Utils 的 StringUtils.deleteWhitespace(str) 從文件標記中刪除空格。for 循環中的 if 條件檢查三個字符的子字符串在字符串中是否可用,如果它不是那么任何字符是離開它將轉到列表。我的文本文件在第一行和第二行包含以下字符串asdfcshgfser ajsnsdxs sasdsd fghfdgfd

執行程序后的結果如下,

列表[asd, fcs, hgf, ser, ajs, nsd, xs, sas, dsd, fgh, fdg, fd]

public ArrayList<String> returnArray()throws FileNotFoundException
     {
        private ArrayList<String> list = new ArrayList<String>();

        Scanner scanCharacters = new Scanner(file);
        String temp = "";

        while (scanCharacters.hasNext())
        {
            temp+=scanCharacters.next();
        }

        while(temp.length() > 2){
               list.add(temp.substring(0,3));
               temp = temp.substring(3);
            }
            if(temp.length()>0){
            list.add(temp);
            }



        scanCharacters.close();

        return list;
    }

在這個例子中,我讀入了文件中的所有數據,然后以三個為一組解析它。 Scanner 永遠不會回溯,因此使用 next 會按照您使用它的方式遺漏一些數據。 您將獲得一組單詞(由空格分隔,Java 的默認分隔符),然后將前 3 個字母分串。 IE:ALEXCY WOWZAMAN 會給你:ALE 和 WOW

我的示例的工作方式是獲取一個字符串中的所有字母,並從三個字母中連續子字符串,直到沒有更多字母,最后,它添加了余數。 就像其他人所說的那樣,最好閱讀不同的數據解析器,例如 BufferedReader。 另外,如果你想繼續使用你目前的方法,我建議你研究子字符串和掃描器。

暫無
暫無

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

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