问题描述:
计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串。
问题示例:
输入“Hello,I am just a student”,输出6。
代码实现:
class Solution:
#参数s:字符串
#返回整数
def countSegments(self,s):
res = 0
for i in range (len(s)):
if s[i] != " " and (i == 0 or s[i -1]==" "):
res +=1
return res
if __name__ == "main":
s=Solution()
n="Hello,I am just a student!"
print("输入:",n)
print("输出:",s.countSegments(n))
运行结果:
输入:Hello,I am just a student
输出:6