1

我的问题是能够计算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(condition) 写什么

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

5 回答 5

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++;
    }
}
于 2014-04-19T12:36:55.330 回答
3

simple-escape-sequence:
任何时候您需要将这 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, '\''));
于 2014-04-19T13:05:53.113 回答
1

您需要使用转义序列。

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

您也可以使用 ascii 值。27 表示 ' 和 22 表示 " 十六进制。

于 2014-04-19T12:38:29.973 回答
1

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

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

查看链接以获取更多信息:C 中的转义序列

于 2014-04-19T12:44:15.737 回答
0

你需要逃避它

if (cmd[i] =='\'')
    cntSingle++;
else if (cmd[i] =='\"')
    cntDouble++;
于 2014-04-19T12:36:45.097 回答