【问题标题】:Find the index of the first space character?找到第一个空格字符的索引?
【发布时间】:2017-10-04 23:53:18
【问题描述】:

我已经编写了功能代码,它将读取和写入数据值到数组列表。虽然它返回所有内容,但如果一个值有多个单词,我该如何排除第一个单词?

  // 3 points
static ArrayList<String> Q2(String filename) {

    // You are given a file (filename) containing a different random phrase on each line. Return an
    // ArrayList containing each phrase, but without the first word of each phrase.
    //
    // Example: If the files contains the 2 phrases "roofed crossover" and "beneficiary charles frederick worth" the
    // ArrayList should contain "crossover" and "charles frederick worth"
    ArrayList<String> al = new ArrayList<String>();

    try {
        for(String s : Files.readAllLines(Paths.get(filename))){


            al.add(s.substring(9));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return al;
}

这是评分员所说的:

Incorrect on input: data/phrases0.txt
Expected output : [algae, blood platelet, charles frederick worth, convert, crossover, eye movement, ferocity, itch, lake albert, loewi, mountainside, peach, sontag, specialty, supposition, surprised endometriosis, testimonial, trial golden fleece, waterproofing, wrongdoer]
Your output     : [ferocity, peach, ed algae, wi, ossover, ry charles frederick worth, ised endometriosis, wrongdoer,  lake albert, ng waterproofing, d eye movement, mountainside, g testimonial, c itch, tal sontag, ive blood platelet, golden fleece, ic specialty, convert, s supposition]

我已经让它在没有第一个字符串的情况下返回一些值,但是有些单词比子字符串可以达到的要大。

【问题讨论】:

  • 我无法理解您的代码逻辑。如果我必须这样做,我不会尝试读取文件的所有行,将它们连接起来,然后拆分逗号字符,然后再次连接。相反,我会阅读每一行,删除其中的第一个单词,然后将结果字符串添加到列表中。然后返回列表。您似乎没有阅读或理解该作业。
  • 第一个字不知道怎么去掉。
  • 这不是一个简单的问题,在现实生活中。但是对于这个练习,我想你可以找到第一个空格字符的索引,然后取这个索引之后的子字符串。
  • 我编辑了它,但我被困在索引部分有没有特定的方法可以做到这一点?
  • 你需要在String中找到indexOf一个字符。阅读String的javadoc应该足以让你找到解决方案。

标签: java file arraylist read-write


【解决方案1】:

您只需要删除空格前的第一个单词,然后只需使用以下代码:从空格字符的位置获取输入字符串的子字符串。

for(String s : Files.readAllLines(Paths.get(filename))){
    al.add(s.substring(s.indexOf(" ")+1)));
}

【讨论】:

    【解决方案2】:

    在遍历拆分字符串时忽略第一项可能是最简单的

        data = "";
        for(String s : Files.readAllLines(Paths.get(filename))){    
             line = s.split(",");
             for (int i = 1; i < line.length; i++) {
                 String data = line[i] + System.getProperty("line.separator");
                 list.add(data);
             }
        }
    

    根据评论,您还需要在输出中使用逗号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-02
      • 2011-05-29
      • 2015-10-07
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多