查找某个字符在C中的字符串中出现多少次

查找某个字符在C中的字符串中出现多少次

本文介绍了查找某个字符在C中的字符串中出现多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find out how many times a character appear in a string.

例如:

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

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

how can I find the number of times character '|' appear in the string?

我还有另一个问题:

是否可以找到字符串是否包含特殊字符?

Is there a way to find if a string contain special character?

EX: netbean&

EX: "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中的字符串中出现多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:33