如何计算单引号或双引号

时间:2014-04-19 12:32:23

标签: 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

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

当我必须在我的字符串中计算'|'时更容易,例如

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

所以我的功能很简单:

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

 return num;
}

但是现在我必须分析报价,我不知道如何为if(条件)付出

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

5 个答案:

答案 0 :(得分:4)

要制作包含单引号的字符,您必须将其转义。否则,它被视为角色的结尾。

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++;
    }
}

答案 1 :(得分:3)

简单转义序列:
无论何时您需要在代码中将这11个字符中的任何一个表示为常量,请使用以下命令:

'\\' (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)

代码重用的好时机:

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, '\''));

答案 2 :(得分:1)

您需要使用转义序列。

if(cmd[i]== '\'') {
    //do something
}

您也可以使用ascii值。 27为&#39;和#34;十六进制。

答案 3 :(得分:1)

在单引号(如\')或双引号(如\")之前,必须使用反斜杠作为转义字符。因此,您必须使用以下语句来检查和计算:< / p>

    if (cmd[i] == '\'')  numOfSingleQuote++;
    else if (cmd[i] == '\"')  numOfDoubleQuote++; 

查看链接以获取更多信息:Escape sequences in C

答案 4 :(得分:0)

你需要逃避它

if (cmd[i] =='\'')
    cntSingle++;
else if (cmd[i] =='\"')
    cntDouble++;