【问题标题】:Find how many times a character appear in string in C找出一个字符在C中的字符串中出现的次数
【发布时间】:2014-11-27 02:40:55
【问题描述】:

我试图找出一个字符在一个字符串中出现了多少次。

例如:

char * line = "cat file1 | grep c | wc"

如何找到字符“|”的次数出现在字符串中?

我还有一个问题:

有没有办法判断一个字符串是否包含特殊字符?

EX: "netbean&"

【问题讨论】:

  • 试试旧的 for (...) 循环和计数器。
  • 试试旧的strstr(),例如。阅读那些手册页,那里有一整套字符串操作函数。
  • 通过char 遍历字符串char 并将每个字符与您想要的字符匹配。如果匹配则增加计数器。最终计数器将显示字符的总出现次数。

标签: c string char


【解决方案1】:

试试这个:

int main(){
  const char *str = "cat file1 | grep c | wc";
  int counts[256] = { 0 };
  int i;
  size_t len = strlen(str);
  for (i = 0; i < len; i++) {
    counts[(int)(str[i])]++;
  }
  for (i = 0; i < 256; i++) {
    if(counts[i]>0)
    printf("%c occurs %d times.\n", i , counts[i]);
  }

    return 0;
}

输出:

  occurs 6 times.
1 occurs 1 times.
a occurs 1 times.
c occurs 3 times.
e occurs 2 times.
f occurs 1 times.
g occurs 1 times.
i occurs 1 times.
l occurs 1 times.
p occurs 1 times.
r occurs 1 times.
t occurs 1 times.
w occurs 1 times.
| occurs 2 times.

【讨论】:

    【解决方案2】:

    一种更简洁/简洁的方式,与(在我看来)冗长的解决方案形成对比:

    size_t count_tokens(const char *str, char token)
    {
      size_t count = 0;
      while(*str != '\0')
      {
        count += *str++ == token;
      }
      return count;
    }
    

    这利用了== 产生值10 的事实,因此我们可以取消内部循环中的if

    【讨论】:

    • 很好的答案(size_t 和所有),但我认为使用 for 循环更习惯,因为迭代器在这里是明确的。
    • 嗯,还是会生成一个cmp,所以很可能是一个if。
    【解决方案3】:

    应该这样做。

    int i;
    int count = 0;
    
    int length = strlen(line);
    
    for (i = 0; i < length; i++) {
        if (line[i] == '|') {
            count++;
        }
    }
    

    【讨论】:

    • 建议每次迭代使用一次 strlen() 在功能上当然是正确的(=它会起作用),但在 C 中也非常非典型。
    • 我的错,凌晨 3 点。该睡觉了。
    • 当然这是一个教育目的,但是使用ints 而不是size_ts 来计数和索引以及使用strlen() 作为循环条件是一个坏习惯,尤其是当它已知不会改变。
    【解决方案4】:
    int c;
    char *str = "hello world";
    for (c = 0; *str != '\0'; str++)
        if (*str == 'o')
            c++;
    

    如果您需要计算多个子字符串,例如“netbean&”,则如下:

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
        char *str = "hello netbean& world netbean&netbean& ooo netbean&";
        char *t;
        int c;
        for (c = 0; *str != '\0';) {
            if ((t = strstr(str, "netbean&")) != NULL) {
                c++; str = t + 1;
            } else {
                break;
            }
        }
        printf("%d\n", c);
    }
    

    【讨论】:

    • Leonardo da Vinci 总是在他们的画作中引入不确定性,让白痴无法复制它
    猜你喜欢
    • 1970-01-01
    • 2015-01-28
    • 2012-10-17
    • 2016-03-19
    • 2021-06-24
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多