找到第一次出现未转义的角色

时间:2012-03-13 00:01:15

标签: c string strchr

找到给定字符串中第一个未转义出现的字符的最佳方法是什么?

我就是这样做的,但我觉得它过于复杂了。

/*
 * 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;
}

1 个答案:

答案 0 :(得分:1)

如果搜索字符相当罕见,那么您的方法是合理的。通常,像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;