Prepare > Python > Strings > Find a string

2023. 7. 4. 20:35HackerRank-Python

 

Find a string | HackerRank

Find the number of occurrences of a substring in a string.

www.hackerrank.com

 

문제


In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.

 

=> string에서 substring이 몇 번 포함돼있는지 세라

예시를 보면, 한 문자가 여러번 카운트 될 수 있음.

 

 

 

 

코드


def count_substring(string, sub_string):
    step = 0

    for j in range(len(string)-len(sub_string)+1):
        if string[j:j+len(sub_string)] == sub_string:
            step = step + 1
 
    return step
 

    
    
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

 

 

 

 

노트


얘는 왜 안될까?

def count_substring(string, sub_string):
    step = 0
    j = 0
    While j <= len(string) - len(sub_string):
        if string[j:j+len(sub_string)] == sub_string:
            step = step + 1
            j = +1
        else: j = +1
    return step

 

another code

def count_substring(string, sub_string):
    count = 0

    for i in range(len(string)):
        if string[i:].startswith(sub_string):
            count += 1
    return count
    

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

 

 

 

참조


 

[Python/Hackerrank] Strings > Find a string

Find a string In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. NOTE: String letter

hoojiv.tistory.com