【问题标题】:Split file having Integers and string into strings only仅将具有整数和字符串的文件拆分为字符串
【发布时间】:2014-03-13 20:09:25
【问题描述】:

我有一个文件,它的数据存储为“整数->\t(tab)->字符串->几个空格->”。

我做错了吗?

我正在做的是。

    Trie t = new Trie();
    BufferedReader bReader = new BufferedReader(new FileReader(
            "H:\\100kfound.txt"));

    String line;
    String[] s = null;
    while ((line = bReader.readLine()) != null) {

        s = line.split("\t");

    }
    int i;
    for (i = 0; i < s.length; i++) {
        System.out.println(s[i]);
        if (!(s[i].matches("\\d+"))) {

            t.addWord(s[i]);
            System.out.println(s[i]);
        }
    }

我可以通过调试看到它在 while 循环中运行正常,但在 for 循环中它只存储两个字符串并打印相同。

【问题讨论】:

  • 你知道你用这段代码扔掉了除了最后一行之外的所有行吗?

标签: java string delimiter trie


【解决方案1】:

您可能希望为表达式添加 ^[0-9]+$,这样您就可以获得完整的整数。如果没有 ^ 和 $,您可能会匹配其他字符,例如 tt55gh 会匹配。

if (!(s[i].matches("^[0-9]+$"))) {
}

根据上面的评论,您需要将 for 循环移到 while 循环内。

while ((line = bReader.readLine()) != null) {

    s = line.split("\t");

    for (int i = 0; i < s.length; i++) {
        System.out.println("Value "+i+": "+s[i]);
        if (!(s[i].matches("^[0-9]+$"))) {
            t.addWord(s[i]);
            System.out.println("Integer "+i+": "+s[i]);
        }
    }
}

【讨论】:

  • 没有缓解乔。我有超过 10000 个字符串的巨大文件。它会影响它吗?
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 2021-12-07
  • 1970-01-01
相关资源
最近更新 更多