Search code examples
javafilearraylistread-write

Find the index of the first space character?


I've written functional code that will read and write data values to an arraylist. Though it returns everything, if a value has multiple words how can I exclude the first one?

  // 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;
}

Heres what the grader says:

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]

I've gotten it to return some values back without the first string however some words are larger than the sub string can reach.


Solution

  • All you need is remove the first word stand before the space, then just use this code: get sub string of input string from position of the space char.

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