返回字符串"hi"
出现在给定字符串中的任何位置的次数。
count_hi('abc hi ho') # → 1
count_hi('ABChi hi') # → 2
count_hi('hihi') # → 2
我有这个解决方案;
def count_hi(str):
return str.count("hi")
但我正在寻找使用给定提示的解决方案:使用for i in range(len(str)-1):
循环查看字符串中的每个索引,除了最后一个。对于每个i
,从i
开始提取字符串,但不包括i+2
。检查该字符串是否为"hi"
,并计算发生的次数。
我甚至试过这个解决方案,但没有通过所有测试用例:
def count_hi(str):
count = 0
for char in str:
if char == 'hi':
count += 1
return count
答案 0 :(得分:2)
这是一个版本:
def count_hi(s):
count = 0
for i in range(len(s)-1):
count += s[i]=='h' and s[i+1]=='i'
return count
这是另一个:
def count_hi2(s):
count = 0
for i in range(len(s)-1):
count += s[i:i+2] == 'hi'
return count
考虑以下代码片段:
for char in str:
if char == 'hi':
这将遍历字符串str
中的各个字符。因此,在此循环中,char
始终是一个单个字符。因此,它永远不会等于两个字符。
此外,最佳做法是为字符串使用不同的名称:str
是内置的。 Python会让你自由地覆盖内置函数,但结果是你将无法轻松访问它们。
答案 1 :(得分:1)
您可以拆分字符串:
string = 'hire test foo hi bar high'
split_string = [[item]+['hi'] for item in string.split('hi') if item != ""]
split_string = sum(split_string, [])
并使用for
循环来计算匹配的字符串:
string_count = 0
for item in range(len(split_string)):
if split_string[item] == 'hi':
string_count += 1
或,您可以跳过for
循环直接计算列表:
split_string.count('hi') # returns 3
答案 2 :(得分:0)
public int countHi(String str) {
int count = 0;
for( int i = 0 ; i < str.length()-1 ; i++){
if ( str.substring(i , i+2).equals("hi"))
count = count + 1;
}
return count;
}
答案 3 :(得分:0)
小帮助:
def count_hi(str):
count = 0
for i in range(len(str)-1):
if str[i] == 'h' and str[i+1] == 'i':
count += 1
return count
答案 4 :(得分:0)
def count_hi(str):
len_w = len(str)
txt = str.replace("hi", "")
len_wo = len(txt)
return (len_w- len_wo)/2
答案 5 :(得分:0)
def count_hi(str1):
#use the replace method to replace all spaces
str1 = list(str1.replace(' ',''))
print(str1)
'''define a counter variable that increments by one everytime the if cond
is met'''
count = 0
for i in range(len(str1)-1):
if str1[i] == "h" and str1[i+1] == "i":
count += 1
return count
答案 6 :(得分:0)
def count_hi(str):
my_list = []
for each in range(len(str) - 1):
if str[each] == "h":
next_item = str[each + 1]
my_list.append(str[each] + next_item)
total = my_list.count("hi")
return total