Question

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]==''')??
Was it helpful?

Solution 2

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

OTHER TIPS

To make a char containing a single quote, you have to escape it. Otherwise, it's treated as the end of the character.

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

You need to use an escape sequence.

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

You could also use the ascii values. 27 for ' and 22 for " in hexadecimal.

You have to use a backslash as an escape character before single quote (Like \' ) or double quote(Like \" ).So,you have to use following statements to check and count :

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

Checkout the link for more : Escape sequences in C

You need to escape it

if (cmd[i] =='\'')
    cntSingle++;
else if (cmd[i] =='\"')
    cntDouble++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top