计算C中字符串中char的出现次数 [英] Counting number of occurrences of a char in a string in C
本文介绍了计算C中字符串中char的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字符串 str
char *str = "100.10b.100.100";
我想统计 '.'
在 str
中的出现次数,最好是单行.(如果可能的话不要循环)
I want to count the occurrences of '.'
in str
, preferably a one-liner. (If possible no loops)
我的方法是标准的 strchr
:
int i = 0;
char *pch=strchr(str,'.');
while (pch!=NULL) {
i++;
pch=strchr(pch+1,'.');
}
推荐答案
这是我的做法(需要最少数量的变量):
Here's the way I'd do it (minimal number of variables needed):
for (i=0; s[i]; s[i]=='.' ? i++ : *s++);
这篇关于计算C中字符串中char的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文