在给定字符串中查找第一个未转义字符的最佳方法是什么?
我就是这样做的,但我觉得这太复杂了。
/*
* 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;
}
如果搜索字符非常罕见,那么您的方法是合理的。一般来说,像strchr
这样的C库例程是用紧凑的机器语言编码的,运行速度几乎比用C编码的任何循环都快。一些型号的硬件有用于搜索内存块的机器指令;一个使用的C库例程,它的运行速度将比你在C.中编写的任何循环都快得多
为了稍微收紧你的方法,这个怎么样:
#define isEven(a) ((a) & 1) == 0)
char* p = strchr( s, c );
while (p != NULL) { /* loop through all the c's */
char* q = p; /* scan backwards through preceding escapes */
while (q > s && *(q-1) == '\')
--q;
if (isEven( p - q )) /* even number of esc's => c is good */
return p;
p = strchr( p+1, c ); /* else odd escapes => c is escaped, keep going */
}
return null;