查找字符在C中出现在字符串中的次数

时间:2014-10-02 06:04:42

标签: c string char

我试图找出一个字符出现在字符串中的次数。

例如:

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

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

我还有另一个问题:

有没有办法查找字符串是否包含特殊字符?

EX:“netbean&”

4 个答案:

答案 0 :(得分:2)

试试这个:

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.

答案 1 :(得分:1)

略微简洁/简洁的方式,与(在我看来)冗长的解决方案形成鲜明对比:

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

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

答案 2 :(得分:0)

应该这样做。

int i;
int count = 0;

int length = strlen(line);

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

答案 3 :(得分:-2)

int c;
char *str = "hello world";
for (c = 0; *str != '\0'; str++)
    if (*str == 'o')
        c++;

如果您需要计算一些子字符串,例如&#34; netbean&amp;&#34;,则接下来是:

#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);
}