tags:

views:

101

answers:

4

What is the escape sequence for ' " ' in C? In other words, how can i ask a while-statement to search for an occurance of ' " '?

+10  A: 

In a character constant, you don't need to escape the " character; you can simply use '"'.

In a string literal, you do need to escape the " character since it's the delimiter; you do this by prefixing it with a backslash ("\"").

Note that you can escape the " character in a character constant ('\"'); it's just not necessary.

James McNellis
You could also use `\x22` in place of `\"` to search for a double-quote in a string
Zabba
@Zabba: If I saw `\x22` in a code review, I'd almost assuredly consider it [a major code WTF](http://28.media.tumblr.com/tumblr_kpu8502s7I1qa3ti5o1_400.jpg).
James McNellis
@james Of course - you should write it as \042
Martin Beckett
+1  A: 

You want to look for "\""

Andrew Cooper
A: 

The character '"', ASCII code 34. "In a string literal you escape it like \" this".

Nikolai N Fetissov
+1  A: 

Use strchr() from string.h

#include <stdio.h>
#include <string.h>

int main ()
{
      char str[] = "This is a sample string with \" another \"";
      char * pch;
      printf ("Looking for the '\"' character in: %s ...\n",str);
      pch=strchr(str,'"');
      while (pch!=NULL)
      {
            printf ("found at %d\n",pch-str+1);
            pch=strchr(pch+1,'\"');
      }
      return 0;
}
Ruel
you really don't need to use string.h for this. `while(*pch++ != '"' ` moves `pch` to the first position of a double quote or until the end of the string.
Mark E
But `strchr` might be several times faster with large strings, due to the ability to search whole words (or whole 16-byte chunks with sse, etc.) at a time.
R..
The flip side is that `strchr` loses the information about the length of the string if the character was not found, so you have to waste `O(n)` time calling `strlen` to find it again if you needed it. An alternative would be `strcspn`, but it's likely not to be optimized for the case of a single character set.
R..