Search code examples
javaarrayssearchphrase

How to split a string into an array of suffixes?


What is the most efficient way to split a string into an array of its suffixes?

Say you have the string "The weather is nice", I want to generate an array of its suffixes as such:

[0] = "nice"

[1] = "is nice"

[2] = "weather is nice"

[3] = "the weather is nice"

I have access to the strings in the form of an iterator over its tokens (words) from start to end.


Solution

  • Split the array on spaces using the split, then go through the resultant tokens back-to-front, take the previous suffix, and prepend the current token to its front. If there is no prior suffix, use an empty string:

    String str = "quick brown fox jumps over the lazy dog";
    List<String> res = new ArrayList<String>();
    String last = null;
    String[] tok = str.split(" ");
    for (int i = tok.length-1 ; i >= 0 ; i--) {
        if (last == null) {
            last = tok[i];
        } else {
            last = tok[i] + " " + last;
        }
        res.add(last);
    }
    for (String s : res) {
        System.out.println(s);
    }
    

    This prints

    dog
    lazy dog
    the lazy dog
    over the lazy dog
    jumps over the lazy dog
    fox jumps over the lazy dog
    brown fox jumps over the lazy dog
    quick brown fox jumps over the lazy dog
    

    Link to a demo on ideone.