summary refs log blame commit diff stats
path: root/python/code/09_str_count.py
blob: 3c0a566cd842f8295e4707fc7781850b7919706c (plain) (tree)
























                                                                           
def our_str_count(s, sub, start=None, end=None):
    ss = s[slice(start, end)]
    if len(sub) == 0: return len(ss) + 1
    elif len(ss) < len(sub): return 0
    i, l, ls = 0, len(ss), len(sub)
    count = 0
    while i < l:
        if ss[i:i+ls] == sub:
            count += 1
            i += ls
        else:
            i += 1
    return count

s = input('Enter a string: ')
sub = input('Enter substring to count: ')
idcs = input('Enter starting and ending indices (default: whole string): ')
if len(idcs) == 0:
    idcs = (None, None)
else:
    idcs = (int(i) for i in idcs.split())
start, end = idcs

print('Count:', our_str_count(s, sub, start, end))