[英]Split string containing “.” without using inbuilt functions
I need to split the string and create a list of words without using inbuilt functions.我需要拆分字符串并创建一个单词列表而不使用内置函数。 Please help I'm missing something in the logic
请帮助我在逻辑中遗漏了一些东西
st="i.like.this.very.much"
wordlist=[]
i=0
j=0
while i<len(st)-4:
if st[i]==".":
i+=1
else:
j=i
word=""
while st[j]!=".":
word+=st[j]
j+=1
print(word)
wordlist.append(word)
i+=len(word)
print(wordlist)
Output: C:\\Users\\Desktop>python raja1.py输出:C:\\Users\\Desktop>python raja1.py
i.like.this.very.much
i
l
li
lik
like
t
th
thi
this
v
ve
ver
very
['i', 'like', 'this', 'very']
Here's a quick-and-dirty solution that doesn't use len()
or append()
(and you can remove print()
later):这是一个不使用
len()
或append()
的快速而肮脏的解决方案(您可以稍后删除print()
):
st="i.like.this.very.much"
sp=[]
c=""
for s in st:
if s == ".":
sp=sp+[c]
c=""
else: c+=s
if s != ".": sp=sp+[c]
print(sp)
The output is ['i', 'like', 'this', 'very', 'much']
.输出是
['i', 'like', 'this', 'very', 'much']
。
Your only problem is that you've neglected to pick up the final word, because you stop 4 characters early for no apparent reason.您唯一的问题是您忽略了最后一个单词,因为您无缘无故提前停止了 4 个字符。 Your loop only dumps the word if it ends with a period.
您的循环仅转储以句点结尾的单词。
Run through the end of the string.穿过字符串的末尾。 Then simply add one more
append
after the loop -- but check that you do have a word to add, in case the input ended with a period:然后简单地在循环之后再添加一个
append
—— 但检查你是否有要添加的单词,以防输入以句点结尾:
if word:
wordlist.append(word)
Also, you say that you can't use any built-ins, but your supposed solution uses len
.另外,您说您不能使用任何内置函数,但您假设的解决方案使用
len
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.