티스토리 뷰

728x90

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 letters are case-sensitive.

 

Input Format

The first line of input contains the original string. The next line contains the substring.

 

Constraints

Each character in the string is an ascii character.

 

Output Format

Output the integer number indicating the total number of occurrences of the substring in the original string.

 

Sample Input

ABCDCDC
CDC

Sample Output

2

Concept

Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the length of a string is found by the function len(s), where  is the string.
To traverse through the length of a string, use a for loop:

for i in range(0, len(s)):
    print (s[i])

A range function is used to loop over some length:

range (0, 5)

Here, the range loops over 0 to 4. 5 is excluded.

 

문제해석

input값으로 string과 substring 2개가 입력된다. string에 substring이 몇 번이나 포함되어 있는지 체크하여 출력하면 된다. 샘플예제에서 string=ABCDCDC, substring=CDC 이렇게 입력되는데 CDC는 총 2번 나온다. 

 

문제풀이

find() 함수는 첫 번째 일치하는 문자열의 위치를 리턴하기 때문에 몇 번 일치하는지 카운트값은 구할 수 없었다. 이 값을 구하려면 문제 컨셉에서 알려준 것처럼 for문을 사용하여 각 문자열을 체크해야 한다고 생각하였다. 그래서 아래 for문을 작성하였다. 

 for i in range(0, len(string)):

이제 for문 안에서 string의 각 문자가 찾을 문자열인 sub_string의 첫 번째 문자와 일치하는지 체크한다. 즉, 샘플의 ABCDCDC의 문자열에서 A, B, C, D, C, D, C 모든 문자를 순서대로 찾을 문자열인 CDC의 C와 일치하는지 체크하는 것이다. 

if string[i] == sub_string[0]:

첫 번째 문자가 일치한 경우에는 string의 해당 위치부터 sub_string의 길이만큼의 문자열이 실제로 찾으려는 sub_string과 동일한지 체크한다. find() 함수의 경우 해당 문자열을 찾지 못한 경우에는 -1이므로 -1이 아닌 경우는 모두 일치하는 경우라 볼 수 있고 이 때에 counter 값을 1 증가시킨다. 

if string.find(sub_string, i, i+len(sub_string)) != -1:                
                counter += 1

최종코드

def count_substring(string, sub_string):
    string = string.replace(" ", "")
        
    i = 0
    counter = 0 
    for i in range(0, len(string)):
        if string[i] == sub_string[0]:
            if string.find(sub_string, i, i+len(sub_string)) != -1:                
                counter += 1                
    return counter   
    
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

Discussions

대체로 비슷하게 푼 것 같은데 아래 startswith() 함수를 사용한 예는 좀 더 간단해 보인다. startswith()는 문자열이 특정 값으로 시작할 경우 true를 반환한다. 즉, string에서 한 문자씩 뒤로 가면서 찾을 문자열로 시작하는지 체크하는 것이다.

def count_substring(string, sub_string):
    count = 0
    for i in range(len(string)):
        if string[i:].startswith(sub_string):
            count += 1
    return count
728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함