【问题标题】:how to count single or double quotes如何计算单引号或双引号
【发布时间】:2014-04-19 12:32:22
【问题描述】:

我的问题是能够计算 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]==''')??

【问题讨论】:

标签: c algorithm text-analysis string-algorithm


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    简单转义序列:
    每当您需要在代码中将这 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, '\''));
    

    【讨论】:

      【解决方案3】:

      您需要使用转义序列。

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

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

      【讨论】:

        【解决方案4】:

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

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

        查看更多链接:Escape sequences in C

        【讨论】:

          【解决方案5】:

          你需要逃避它

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

          【讨论】:

          • 你不需要转义双引号。
          • 另外,你没有单独计算它们。
          • @Barmar 使用双引号而不转义,导致您在使用 char 数组时遇到麻烦。同样之前我没有回答计数方式,而是他应该逃避角色的方式,因为他不知道
          • 这是单个字符,而不是字符串。您只需转义用于分隔它的字符 - 转义字符中的单引号,转义字符串中的双引号。
          猜你喜欢
          • 2011-03-09
          • 1970-01-01
          • 2011-07-22
          • 2012-10-16
          • 1970-01-01
          • 2018-06-13
          • 2011-09-17
          • 2012-12-13
          • 1970-01-01
          相关资源
          最近更新 更多