Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find and count all the occurrences of a substring in a string using only find and replace?

The entry needs to be lower and in the end the program must print the number of occurrences. For example mem.

smthing = str(input())
if (smthing == smthing.lower()):
    smthing.find(mem)

I'm a total wreck at this so I couldnt go far.

I forgot to tell that I can't use count or list.

like image 229
useruseruser Avatar asked Dec 05 '25 10:12

useruseruser


2 Answers

What about something like

string = "hello world hello".lower()
replace = "hello".lower()
count = 0

while string.find(replace) != -1:
    string = string.replace(replace, "", 1)
    count += 1

print count
# => Output
# => 2

To take care of the overlapping strings, instead of replacing the entire substring, we could just replace a single character, preferably the first, replace[0] from the original string

string = "boboobobobobob".lower()
replace = "bob".lower()
count = 0 

while string.find(replace) != -1:
    string = string.replace(replace[0], "", 1)
    count += 1

print count
# Output
# => 6
like image 67
nu11p01n73R Avatar answered Dec 06 '25 23:12

nu11p01n73R


If you have overlapping strings you will need to replace a character a a time:

sub = "bob"
smthing = input()
count = 0

for i in iter(lambda: smthing.find(sub), -1):
    smthing = smthing.replace(sub[0], "", 1)
    count += 1
print(count)

So for boboobobobobob you would get 6 instead of 3.

If you can't use a count but can use either one or the other you could use replace alone, though this won't include overlapping:

print((len(smthing) - len(smthing.replace(sub,""))) / len(sub))
like image 39
Padraic Cunningham Avatar answered Dec 07 '25 00:12

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!