查找一个名字在字符串中出现的次数

huangapple go评论59阅读模式
英文:

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(&quot;Hamza&quot;);

  while (index != -1) {
    count++;
    index = str.indexOf(&quot;Hamza&quot;, index + 1);
  }

  return count;
}

let string = &quot;Hamza flew his kite today. But Hamza forgot to play basketball&quot;;
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...

&#39;H&#39;==&#39;Hamza&#39; which returns False
&#39;a&#39;==&#39;Hamza&#39; which returns False
&#39;m&#39;==&#39;Hamza&#39; 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(&#39;Hamza&#39;)

huangapple
  • 本文由 发表于 2023年2月9日 03:24:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定