Search code examples
javaarraysstringextractprefix

Extract words from an array of Strings in java based on conditions


I am trying to do an assignment that works with Arrays and Strings. The code is almost complete, but I've run into a hitch. Every time the code runs, it replaces the value in the index of the output array instead of putting the new value in a different index. For example, if I was trying to search for the words containing a prefix "b" in the array of strings, the intended output is "bat" and "brewers" but instead, the output comes out as "brewers" and "brewers". Any suggestions? (ps. The static main method is there for testing purposes.)

--

public static void main(String[] args) {

    String[] words = {"aardvark", "bat", "brewers", "cadmium", "wolf", "dastardly", "enigmatic", "frenetic",
            "sycophant", "rattle", "zinc", "alloy", "tunnel", "nitrate", "sample", "yellow", "mauve", "abbey",
            "thinker", "junk"};
    String prefix = "b";
    String[] output = new String[wordsStartingWith(words, prefix).length];
    output = wordsStartingWith(words, prefix);

    for (int i = 0; i < output.length; i++) {
        System.out.println("Words: " + i + " " + output[i]);
    }

}

public static String[] wordsStartingWith(String[] words, String prefix) {
    // method that finds and returns all strings that start with the prefix

    String[] returnWords;
    int countWords = 0;

    for (int i = 0; i < words.length; i++) {
        // loop to count the number of words that actually have the prefix
        if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
            countWords++;
        }
    }

    // assign length of array based on number of words containing prefix
    returnWords = new String[countWords];

    for (int i = 0; i < words.length; i++) {
        // loop to put strings containing prefix into new array
        for (int j = 0; j < returnWords.length; j++) {
            if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
                returnWords[j] = words[i];
            }
        }
    }

    return returnWords;
}

--

Thank You

Soul


Solution

  • Its because of the code you have written. If you would have thought it properly you would have realized your mistake.

    The culprit code

    for (int j = 0; j < returnWords.length; j++) {
        if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
            returnWords[j] = words[i];
        }
    }
    

    When you get a matching word you set whole of your output array to that word. This would mean the last word found as satisfying the condition will replace all the previous words in the array.

    All elements of array returnWords gets first initialized to "bat" and then each element gets replaced by "brewers"

    corrected code will be like this

    int j = 0;
    for (int i = 0; i < words.length; i++) {
        if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
            returnWords[j] = words[i];
            j++;
        }
    }
    

    Also you are doing multiple iterations which is not exactly needed.

    For example this statement

    String[] output = new String[wordsStartingWith(words, prefix).length];
    output = wordsStartingWith(words, prefix);
    

    can be rectified to a simpler statement String[] output = wordsStartingWith(words, prefix);