如何计算单引号或双引号

Cod*_*-JR 2 c algorithm text-analysis string-algorithm

我的问题是能够计算c中字符串中单引号或双引号的数量。例子

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

     "hello world"                0                      2
     "hello" world"               0                      3
Run Code Online (Sandbox Code Playgroud)

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

例如,当我必须计算字符串中的“|”时,会更容易

        String            | Count        
     hello | world           1            
     hello | wo|rld          2            
Run Code Online (Sandbox Code Playgroud)

所以我的功能很简单:

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

 return num;
}
Run Code Online (Sandbox Code Playgroud)

但现在我必须分析报价,我不知道该为 if(condition) 添加什么

          if(cmd[i]==''')??
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

要使字符包含单引号,您必须对其进行转义。否则,它被视为字符的结尾。

int numSingle = 0, numDouble = 0;
int i;
for (i = 0; cmd[i] != 0; i++) { // Don't call strlen() every time, it's N**2
    if (cmd[i] == '\'') {
        numSingle++;
    } else if (cmd[i] == '"') {
        numDouble++;
    }
}
Run Code Online (Sandbox Code Playgroud)