[英]Return the number of times that the string "code" appears anywhere in the given string
[英]Return the number of times that the string appears using loops
返回字符串"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
這是一個版本:
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 可以讓您自由地覆蓋內置函數,但結果是您將無法輕松訪問它們。
您可以拆分字符串:
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
返回字符串"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):
使用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
def count_hi(str):
len_w = len(str)
txt = str.replace("hi", "")
len_wo = len(txt)
return (len_w- len_wo)/2
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
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
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.