我编写了功能代码,用于读取和写入数据值到arraylist。虽然它会返回所有内容,但如果某个值有多个单词,我该如何排除第一个?
// 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]
我已经让它在没有第一个字符串的情况下返回一些值,但有些字大于子字符串可以达到的值。
答案 0 :(得分:1)
在迭代拆分字符串
时,忽略第一项可能最容易 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);
}
}
根据评论,你的输出中也需要逗号。
答案 1 :(得分:1)
你需要的只是删除空格前的第一个单词,然后使用这个代码:从空格char的位置获取输入字符串的子字符串。
for(String s : Files.readAllLines(Paths.get(filename))){
al.add(s.substring(s.indexOf(" ")+1)));
}