在计数在C字符串的字符出现的次数 [英] Counting number of occurrences of a char in a string in C

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

问题描述

我有字符串 STR

 的char *海峡=100.10b.100.100;

我要计算的出现。 STR ,preferably一个班轮。 (如果可能的话没有循环)

我的做法是标准的和strchr

  INT I = 0;
  字符* PCH =和strchr(STR,'。');
  而(PCH!= NULL){
    我++;
    PCH =和strchr(PCH + 1,。);
  }


解决方案

下面就是我想要做的方式(最少数量的所需变量):

 为(i = 0; S [I],S [I] ==我++'。'?* S +);

I have the string str

char *str = "100.10b.100.100";

I want to count the occurrences of '.' in str, preferably a one-liner. (If possible no loops)

My approach would be the standard 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字符串的字符出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆