String Program in Python

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


def count_substring(string, sub_string):

count = 0

# Staring the loop with zero and lengh should be len(mainstring) -len(substring)

# len(ABCDCDC)-len(CDC)=7-3=4

for i in range(0, len(string)-len(sub_string)+1):

l = i # Assigning index i value to l

for j in range(0, len(sub_string)):

# Comparing index characters

if string[l] == sub_string[j]:

l +=1

#matching lenght of loop index and substring , if matches then increasing count

if j == len(sub_string)-1:

count = count + 1

else:

continue

else:

break

return count


#Method 2

def count_string(string, substring):

#running the loop till length of main string

count=0

for i in range(len(string)):

#using startwith function

if(string[i:].startswith(substring)):

count=count+1

return count


s1=input("Enter First String")

s2=input("Enter Second String")

print(count_string(s1,s2))

Enter First Stringramkrishnramkrishnram

Enter Second Stringram

3