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

例如:

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


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

我还有另一个问题:

有没有一种方法可以查找字符串是否包含特殊字符?

例如:“ netbean&”

最佳答案

尝试这个 :

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.

关于c - 查找某个字符在C中的字符串中出现多少次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26155225/

10-13 03:38