gpt4 book ai didi

c - 查找第一次出现的未转义字符

转载 作者:行者123 更新时间:2023-11-30 15:58:31 26 4
gpt4 key购买 nike

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

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

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

关于c - 查找第一次出现的未转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9676555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com