summary refs log tree commit diff stats
path: root/python/code/09_str_count.py
blob: 3c0a566cd842f8295e4707fc7781850b7919706c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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))