简体   繁体   中英

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.

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

If you have overlapping strings you will need to replace a character aa 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))

Try this code:

smthing = "blablabla"
mem = "bl"
count = 0
if (smthing == smthing.lower()):
    bkpsmthing = smthing # maybe you'll need it later
    while (smthing.find(mem) > -1):
        smthing = smthing.replace(mem, '', 1)
        count += 1
print count

It uses the fact that str.find returns -1 when not finding anything, or the index to the lowest entry to stop:

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure.

It also uses the fact that str.replace can remove a single entry (the lowest) by using the thrid argument ( maxreplace ). This way we constantly remove entries we've counted:

... If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

The process can be described like this:

find "bl" in "blablabla" -> found at index 0
replace "bl" in "blablabla" -> gives "ablabla"
find "bl" in "ablabla" -> found at index 1
replace "bl" in "ablabla" -> gives "aabla"
find "bl" in "aabla" -> found at index 2
replace "bl" in "aabla" -> gives "aaa"
find "bl" in "aaa" -> not found, returns -1
stop

To do the same thing withtout the count variable use this simple recursion (amke sure you validate the string is lowercase before using my_count ):

def my_count(my_string, my_substring):
    if my_string.find(my_substring) > -1:
        new_string = my_string.replace(my_substring, '', 1)
        return my_count(new_string, my_substring) + 1
    return 0

Output:

>>> my_count("blablabla", "bl")
3

The recursion unfolds as follows:

my_count("blablabla", "bl") =
= my_count("ablabla", "bl") + 1 =
= my_count("aabla", "bl") + 1 + 1 =
= my_count("aaa", "bl") + 1 + 1 + 1 =
= 0 + 1 + 1 + 1 = 3

You don't; you will require additional tools, possibly just basic arithmetic. For instance, if you replace your substring with one of a different length, the result's length can be compared to the original to count the number of occurences. Another option is to use the start argument to find to find additional occurences. I'm rather interested in knowing what you've tried; the code you show simply doesn't produce any result.

For the record, you could do this with just string.replace() :

smthing = str(input())  
word='mem'
x=0

while word in smthing:
    smthing=smthing.replace(word,'',1)
    x+=1

print x

Demo:

>>> 
memory memory memory
3

Your problem -- finding and counting all the occurrences of a substring in a string -- doesn't necessitate replacing as defined.

You should be able to just take your input, force it to lower, and use the count method to find substrings.

num_substrings = input().lower().count(substring)

I don't see this approach yet, just loop over find counting occurences :

a='this is a test aaaa'
count =0
loc = a.find('is')
while loc > -1:
    count += 1
    loc = a.find('is',loc+1)
print count -1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM