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
2010-10-07 03:49:57
You could also use `\x22` in place of `\"` to search for a double-quote in a string
Zabba
2010-10-07 03:59:23
@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
2010-10-07 04:02:34
@james Of course - you should write it as \042
Martin Beckett
2010-10-07 04:15:37
A:
The character '"'
, ASCII code 34. "In a string literal you escape it like \" this"
.
Nikolai N Fetissov
2010-10-07 03:52:33
+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
2010-10-07 03:54:05
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
2010-10-07 03:56:16
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..
2010-10-07 04:05:23
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..
2010-10-07 04:07:10