【问题标题】:Using loops for counting characters in string up to certain point使用循环计算字符串中的字符直到某个点
【发布时间】:2020-03-28 20:11:57
【问题描述】:

我正在尝试编写一个函数来计算字符串中的字符数,直到找到 0,并且直到那时才计数。例如,如果我们有一个字符串“hello0bye”,它只会计算“hello”中的字符数。

我知道有strlen,但我不确定如何在其中实现0。我正在尝试使用 for 循环或 while 循环来编写它。谢谢!

【问题讨论】:

  • 测试每个字符,直到找到'0'
  • strchr(str,'0') - str。如果0 在字符串中,则此方法有效!
  • man strcspn "... 它计算 s 的第一个字符的字符串数组索引,它也在 charset 中,否则计算第一个空字符的索引。"

标签: c


【解决方案1】:

这样的?

#include <stdio.h>
#include <stdlib.h>

int count_char_until_zero(char *str);

int main() {

  int i = count_char_until_zero("kaja0pia");
  printf("Char num until zero: %d\n", i);
  return 0;
}

int count_char_until_zero(char *str) {
  int i = 0;
  while(str[i] != '0') {
      i++;
  }
  return i; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-10
    • 2022-01-03
    • 2021-06-26
    • 2011-06-18
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多