英文:
Finding the number of times a name is in a string
问题
string = "Hamza flew his kite today. But Hamza forgot to play basketball"
def count_name():
count = 0
for sub_str in string:
if sub_str == "Hamza":
count += 1
return count
print(count_name())
My goal here was to find the number of times the name "Hamza", appears in the string.
But it keeps returning 0, instead of 2.
I tried setting the variable count = 0, so it can count how many times the name "Hamza" appears in the string.
英文:
string = "Hamza flew his kite today. But Hamza forgot to play basketball"
def count_name():
count = 0
for sub_str in string:
if sub_str == "Hamza":
count += 1
return count
print(count_name())
My goal here was to find the number of times the name "Hamza", appears in the string.
But it keeps returning 0, instead of 2.
I tried setting the variable count = 0, so it can count how many times the name "Hamza" appears in the string.
答案1
得分: 1
countName 函数接受一个字符串作为参数,并返回其中包含“Hamza”出现的次数。以下是一种统计给定字符串中“Hamza”出现次数的方法:
function countName(str) {
let count = 0;
let index = str.indexOf("Hamza");
while (index != -1) {
count++;
index = str.indexOf("Hamza", index + 1);
}
return count;
}
let string = "Hamza flew his kite today. But Hamza forgot to play basketball";
let count = countName(string);
console.log(count); // 输出: 2
英文:
The countName function takes a string as an argument and returns the number of times "Hamza" appears in it. Here is one way to count the number of times "Hamza" appears in a given string:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function countName(str) {
let count = 0;
let index = str.indexOf("Hamza");
while (index != -1) {
count++;
index = str.indexOf("Hamza", index + 1);
}
return count;
}
let string = "Hamza flew his kite today. But Hamza forgot to play basketball";
let count = countName(string);
console.log(count); // Output: 2
<!-- end snippet -->
答案2
得分: 1
当你使用for sub_str in string:
时,你是逐个字母查看而不是逐个单词。你正在检查...
'H'=='Hamza' 返回False
'a'=='Hamza' 返回False
'm'=='Hamza' 返回False...
这就是为什么你的计数永远不会增加。
幸运的是,Python有内置方法可以让你的生活变得更容易。
尝试string.count('Hamza')
英文:
when you do for sub_str in string:
you are looking at one letter a time (not one word at a time). You are checking...
'H'=='Hamza' which returns False
'a'=='Hamza' which returns False
'm'=='Hamza' which returns False...
that is why your count will never increase.
Luckily for you python has built in methods to make your life easy.
Try string.count('Hamza')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论