Вот довольно эффективное решение, оно требует только одного прохода над строкой.
Мы отслеживаем начало следующей строки как line_start_index
, затем итерируем по каждому символу и отслеживаем последний пробел рассматривается как line_end_index
.
Каждый раз, когда мы повторяем 6 символов из line_start_index
, мы знаем, что следующая строка - это подстрока s[line_start_index:line_end_index]
. Затем мы устанавливаем line_start_index
как конец предыдущей строки.
line_start_index = 0
line_end_index = 0
total = 0
for i, c in enumerate(s):
if c == ' ':
line_end_index = i
if i - line_start_index == 6:
# TODO: Handle words longer than 6 chars (line_start_index == line_end_index + 1)
print('Found line!', s[line_start_index:line_end_index])
total += 1
line_start_index = line_end_index + 1
# For the data you have given there will be one additional line after the loop
# this may not be correct if the last char is a space
print('Found line!', s[line_start_index:])
total += 1
print(total)
Это дает вывод:
Found line! a bcd
Found line! e f
Found line! ghi j
Found line! k lmn
Found line! opq
Found line! ghfdj
Found line! ashks
7
Это не будет работать, если слово длиннее 6 chars, но, как вы сказали, нет необходимости обрабатывать это