Home > Software engineering >  How do I get a string to match substrings in an arraylist?
How do I get a string to match substrings in an arraylist?

Time:01-02

I want to write a method that counts the occurrences of a word in an ArrayList.

However, the word does not have to match a word in the ArrayList, for example completely, the word can be "programming" and the ArrayList can contain [program, java, ming, array].

The example should return a count of 2 since both "program" and "ming" are part of "programming". I would also like the method to accept both upper- and lowercase.

How to solve this?

public class WordsCounter {
    
    public static int occurances(String word, List<String> words) {
        int count = 0;
            for (int i = 0; i < words.size(); i  ) {
                if (words.get(i).equalsIgnoreCase(word)) {
                    count  ;
            } 
        }
        return count;
    }
}

CodePudding user response:

Your current for loop will take the word 'program' and test if it equals 'programming', which it doesn't.

If you changed the code to test if word.contains(words.get(i)) then you'll be testing if 'programming' contains 'program', which it does.

You'll have to handle case though. You could simply use toLowerCase() on both strings first

CodePudding user response:

You could use contains() for this purpose:

public static int occurrences(String word, List<String> words) {
    int count = 0;
    for (String s : words) {
        if (word.contains(s)) {
            count  ;
        }
    }
    return count;
}

Demo:

public static void main(String[] args) {
    List<String> list = List.of("program", "java", "ming", "array");
    System.out.println(occurrences("programming", list));
}

Output:

2

For support upper/lower case you should use the word and element from the list with the same case:

word.toLowerCase().contains(s.toLowerCase())

  • Related