怎么算单或双引号 [英] how to count single or double quotes

查看:248
本文介绍了怎么算单或双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是能够得到一个字符串在C单或双引号的数目。 例如

 字符串单引号计数双引号计数
     世界你好2 0
     hell'o世界3 0

     世界你好0 2
     你好世界0 3
 

用户输入的字符串,我需要通过获得()函数,然后我需要这个计数器来进一步分析该字符串。

这是比较容易的时候我不得不指望'|'在我的字符串,例如:

 字符串|计数
     你好|世界1
     你好|禾| RLD 2
 

所以我的功能就是这么简单:

  INT getNumPipe(字符* CMD){
  INT NUM = 0;
  INT I;
     对于(i = 0; I< strlen的(CMD);我++){
       如果(CMD [我] =='|'){//如果(条件)
       NUM ++;
      }
     }

 返回NUM;
}
 

但现在,我就来分析我不知道放什么了引号,如果(条件)

 如果(CMD [我] ==''')?
 

解决方案

简单的转义序列:
任何时候你需要前preSS任何这11个字符,在code恒定的,使用如下:

 '\\'(反斜线)
'\'' (引用)
\(双引号)
'\? (问号)
'\一个'(报警)
\ B'(退格键)
'\ F'(换)
'\ N'(新行)
'\ R'(回车)
\ t(水平制表)
\ V'(垂直制表)
 

好时机code再利用:

  INT getNumPipe(为const char * CMD,字符匹配){
  INT NUM = 0;
  而(*在cmd!='\ 0'){
    如果(* CMD ==匹配)NUM ++;
    CMD ++;
    }
  返回NUM;
}

...
个char [100];
与fgets(S,sizeof的S,标准输入);
的printf(\的发生%d次\ N,getNumPipe(S,'\'));
的printf(\'发生%d次\ñ,getNumPipe(S,'\''));
 

my problem is to be able to count the number of single or double quotes in a string in c. example

        String            Single Quote Count        Double Quote Count
     'hello world'                2                      0
     'hell'o world'               3                      0

     "hello world"                0                      2
     "hello" world"               0                      3

user enters string, i take by gets() function, and then i need this counter to further analyse the string.

It was easier when i had to count '|'in my string, for example

        String            | Count        
     hello | world           1            
     hello | wo|rld          2            

so my function was as simple as :

 int getNumPipe(char* cmd){
  int  num = 0;
  int i;
     for(i=0;i<strlen(cmd);i++){
       if(cmd[i]=='|'){ //if(condition)
       num++;
      }
     }

 return num;
}

But now that i have to analyse the quotes i dont know what to put for the if(condition)

          if(cmd[i]==''')??

解决方案

simple-escape-sequence:
Anytime you need to express any of these 11 characters as a constant in code, use the following:

'\\' (backslash)
'\'' (quote)
'\"' (double quote)
'\?' (question mark)
'\a' (alarm)
'\b' (backspace)
'\f' (form feed)
'\n' (new line)
'\r' (carriage return)
'\t' (horizontal tab)
'\v' (vertical tab)

Good time for code re-use:

int getNumPipe(const char* cmd, char match) {
  int  num = 0;
  while (*cmd != '\0') {
    if (*cmd == match) num++;
    cmd++;
    }
  return num;
}

...
char s[100];
fgets(s, sizeof s, stdin);
printf(" \" occurs %d times.\n", getNumPipe(s, '\"'));
printf(" \' occurs %d times.\n", getNumPipe(s, '\''));

这篇关于怎么算单或双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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