【问题标题】:Split string with three words用三个单词分割字符串
【发布时间】:2014-03-05 16:46:57
【问题描述】:

拆分包含三个单词的字符串的最佳方法是什么?

我的代码现在看起来像这样(更新代码见下文):

BufferedReader infile = new BufferedReader(new FileReader("file.txt"));

        String line;
        int i = 0;

        while ((line = infile.readLine()) != null) {
            String first, second, last;
            //Split line into first, second and last (word)

            //Do something with words (no help needed)
            i++;
        }

这是完整的文件.txt:

Allegrettho     Albert          0111-27543
Brio            Britta          0113-45771
Cresendo        Crister         0111-27440
Dacapo          Dan             0111-90519
Dolce           Dolly           0116-31418
Espressivo      Eskil           0116-19042
Fortissimo      Folke           0118-37547
Galanto         Gunnel          0112-61805
Glissando       Gloria          0112-43918
Grazioso        Grace           0112-43509
Hysterico       Hilding         0119-71296
Interludio      Inga            0116-22709
Jubilato        Johan           0111-47678
Kverulando      Kajsa           0119-34995
Legato          Lasse           0116-26995
Majestoso       Maja            0116-80308
Marcato         Maria           0113-25788
Molto           Maja            0117-91490
Nontroppo       Maistro         0119-12663
Obligato        Osvald          0112-75541
Parlando        Palle           0112-84460
Piano           Pia             0111-10729
Portato         Putte           0112-61412
Presto          Pelle           0113-54895
Ritardando      Rita            0117-20295
Staccato        Stina           0112-12107
Subito          Sune            0111-37574
Tempo           Kalle           0114-95968
Unisono         Uno             0113-16714
Virtuoso        Vilhelm         0114-10931
Xelerando       Axel            0113-89124

@Pshemo 建议的新代码:

public String load() {
    try {
        Scanner scanner = new Scanner(new File("reg.txt"));

        while (scanner.hasNextLine()) {
            String firstname = scanner.next();
            String lastname = scanner.next();
            String number = scanner.next();
            list.add(new Entry(firstname, lastname, number));
        }
        msg = "The file reg.txt has been opened";
        return msg;
    } catch (NumberFormatException ne) {
            msg = ("Can't find reg.txt");
            return msg;
    } catch (IOException ie) {
            msg = ("Can't find reg.txt");
            return msg;
    }
}

我收到多个错误,怎么了?

【问题讨论】:

  • 您需要使用String#split,但需要知道在哪里拆分字符串。
  • 给出样本输入输出..分割的标准是什么?
  • 你需要用"\\s+"拆分。
  • 您的代码(添加了msglist)在您提供的文件中对我来说很好用。可能问题出在其他地方。我建议使用完整但简化的代码mcve 和可用于重现您的问题的数据创建新问题。还要确保您的数据文件中确实没有空行(就像它的末尾一样)。
  • 您可以将scanner.hasNextLine() 更改为scanner.hasNext()。您的代码的可读性会降低,但这样一来,如果真的有下一个(非空格)元素要读取,您就只能使用scanner.next()。此外,这仅适用于第一个元素 (firstname ),因此如果行不包含三个元素,您将看到 lastnamenumber 的相同错误。

标签: java string loops split


【解决方案1】:

假设每行总是包含三个单词而不是 split,您可以简单地对每行使用 Scanners 方法 next 三次。

Scanner scanner = new Scanner(new File("file.txt"));
int i = 0;
while (scanner.hasNextLine()) {
    String first = scanner.next();
    String second = scanner.next();
    String last = scanner.next();
    //System.out.println(first+": "+second+": "+last);
    i++;
}

【讨论】:

  • 你能看看上面的代码,看看有什么问题吗?它猜测这是错误的捕获语句。
【解决方案2】:
line.split("\\s+"); // don't use " ". use "\\s+" for more than one whitespace

【讨论】:

    【解决方案3】:

    假设该行有 3+ 个单词,使用 split(delimiter) 方法:

    String line = ...;
    
    String[] parts = line.split("\\s+"); // Assuming words are separated by whitespaces, use another if required
    

    那么就可以分别访问第一个、第二个和最后一个了:

    String first = parts[0];
    String second = parts[1];
    String last = parts[parts.length() - 1];
    

    记住索引从 0 开始。

    【讨论】:

    • 假设我在不创建数组的情况下处理每个字符串。我该怎么写呢?
    • split 自动创建一个数组,没有办法。
    • 好的,如果我不使用split 那么呢?很抱歉改变主意,但我认为可以在不创建数组的情况下使用split。感谢您到目前为止的帮助。
    • @mouduor - 提供示例输出。我们可以告诉你 split() 是否是一个不错的选择
    • 我正在使用类 Entry 将单词保存到列表中。 list.add(new Entry(first, second, last));
    【解决方案4】:
    String []parts=line.split("\\s+");
    
    System.out.println(parts[0]);
    System.out.println(parts[1]);
    System.out.println(parts[parts.length-1]);
    

    【讨论】:

    • split(" ") 基于单个空格进行拆分。 split("\\s+") 基于 1 个或多个空格进行拆分。
    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多