Find a string

Sort by

recency

|

3424 Discussions

|

  • + 0 comments

    def count_substring(string, sub_string): j=0 for i in range(len(string)+1): if(string.find(sub_string,i,i+len(sub_string))>=0) : j = j+1 return j

  • + 0 comments
    def count_substring(string, sub_string):
        count = 0
        next_index = 0
        
        while True:
            found_index = string.find(sub_string, next_index)
            if found_index >= 0:
                count += 1
                next_index = found_index + 1
            else:
                return count
    
  • + 0 comments
    count = 0
    start = 0
    while start <= len(string) - len(sub_string):
        pos = string.find(sub_string, start)
        if pos != -1:
            count += 1
            start = pos + 1
        else:
            break
    return count
    
  • + 0 comments
    def count_substring(string, sub_string):
        count = 0
        found = string.find(sub_string)
        
        while found != -1:
            count += 1
            found = string.find(sub_string, found + 1)
            
        return count
    
  • + 1 comment

    Need Help!
    Can anyone help me understand what is wrong with my code? I keep trying to understand but i cant get it right.

    def count_substring(string, sub_string):
        cout = 0
        flag = False
        l2 = list(sub_string)
        n2 = len(sub_string)
        l1 = list(string)
        n1 = len(string)
        for i in range(n1-n2+1):
            if l1[i]==l2[0]:
                for x in range(n2):
                    if l1[i+x] == l2[x]:
                        flag = True
                    else:
                        flag = False
                if flag:
                    cout+=1
                    flag = False
        
        return cout
    
    if __name__ == '__main__':
        string = input().strip()
        sub_string = input().strip()
        
        count = count_substring(string, sub_string)
        print(count)
    
    • + 2 comments

      I think the issue is that you are overcomplicating it (too many lines), so you'll likely make lots of hard to fix small errors.

      I recommend restarting from scratch with online help.

      • + 0 comments

        I've already done it. Yep had to start from the scratch. BTW thanks for the response. 😊