Home > Back-end >  How to count how many times a substring appears in string
How to count how many times a substring appears in string

Time:10-21

Say I have a string of s1 and s2. I wanted to be able to make a program which tells how many times s1 appears in s2. This is my attempt:

char1 = int(input("number of character of s1: "))
s1 = str(input("insert string 1: "))
char2 = int(input("number of character of s2: "))
s2 = str(input("insert string 2: "))
n = 0
bool = True
start = 0
while bool:
    a = s2.find(s1,start)                    
    if a == -1:          
        bool = False
    else:                
        n =1        
        start = a 1
print("s1 appears", n, "times in s2.")

For instance I have s1 as "the" and s2 as "the bird the apple the chair" then the output should be:

s1 appears 3 times in s2.

The problem is, I can't use some functions such as: find, sum, count, max, min, len, try, break, etc.

I'm still a few days old learning python, which is no wonder why I'm still learning array and string--and I can't think of a way for the alternative of the find function that I code. I know I'm very close to get the desired output (since my code actually works), however the find() function is banned

CodePudding user response:

You could use a comprehension / generator expression to match and count -

times = sum(1 if word == s1 else 0 for word in s2.split())
print(f's1 appears {times} times in s2') 

Output

s1 appears 3 times in s2

CodePudding user response:

You could repeatedly compare the wanted string to slices of the target string. For instance, with "the", you could take slices [0:3], [1:4], etc... until you find your match. Return the index of the slice you found plus the the length of the search word and that is the basis for the next find.

(Note: Purposely avoiding len())

def my_find(to_find, string, start=0):
    find_len = 0
    for _ in to_find:
        find_len  = 1
    string_len = 0
    for _ in string:
        string_len  = 1
    for i in range(start, string_len - find_len):
        if string[i:i find_len] == to_find:
            return i   find_len
    return -1

s1 = "the"
s2 = "the bird the apple the chair"

n = 0
bool = True
start = 0
while bool:
    a = my_find(s1, s2, start)               
    if a == -1:          
        bool = False
    else:                
        n =1        
        start = a 1
print("s1 appears", n, "times in s2.")

CodePudding user response:

You may want to consider using the split() method of string so you can iterate through each word in s2. This makes it so you don't have to do any string manipulation or use any functions like find.

s1 = str(input("insert string 1: "))
s2 = str(input("insert string 2: "))

n=0
for word in s2.split():
    if s1 == word:
        n =1

print(f'"{s1}" appears {n} times in "{s2}"')
  • Related