在给定字符串中查找第一个未转义字符的最佳方法是什么?
我就是这样做的,但我觉得它过于复杂。
/*
* Just like strchr, but find first -unescaped- occurrence of c in s.
*/
char *
strchr_unescaped(char *s, char c)
{
int i, escaped;
char *p;
/* Search for c until an unescaped occurrence is found or end of string is
reached. */
for (p=s; p=strchr(p, c); p++) {
escaped = -1;
/* We found a c. Backtrace from it's location to determine if it is
escaped. */
for (i=1; i<=p-s; i++) {
if (*(p-i) == '\\') {
/* Switch escaped flag every time a \ is found. */
escaped *= -1;
continue;
}
/* Stop backtracking when something other than a \ is found. */
break;
}
/* If an odd number of escapes were found, c is indeed escaped. Keep
looking. */
if (escaped == 1)
continue;
/* We found an unescaped c! */
return p;
}
return NULL;
}