Q:

find all occurrences of a substring in a string

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]
1
public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}
0
public List<Integer> findWordUpgrade(String textString, String word) {    List<Integer> indexes = new ArrayList<Integer>();    StringBuilder output = new StringBuilder();    String lowerCaseTextString = textString.toLowerCase();    String lowerCaseWord = word.toLowerCase();    int wordLength = 0;     int index = 0;    while(index != -1){        index = lowerCaseTextString.indexOf(lowerCaseWord, index + wordLength);  // Slight improvement        if (index != -1) {            indexes.add(index);        }        wordLength = word.length();    }    return indexes;}
0

New to Communities?

Join the community