C语言 C语言中字符串查找字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2963394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:34:22  来源:igfitidea点击:

finding character in string C language

c

提问by boom

I am searching a character at first occurence in string using the following code. But it is taking some time when the character is too long or the character that I am searching is at far extent, which delays other operations. How could I tackle this problem. The code is below here.

我正在使用以下代码在字符串中第一次出现时搜索字符。但是当字符太长或我搜索的字符很远时,会花费一些时间,从而延迟其他操作。我该如何解决这个问题。代码在下面。

Note: attrPtris a char *which holds a reference to a string containing '"'character at far extent.

注意:attrPtris achar *保存对包含'"'远距离字符的字符串的引用。

int position = 0;

char qolon = '"';//character to search

while (*(attrPtr + position++) != qolon);

char* attrValue = NULL;

attrValue = (char*)malloc(position * sizeof(char));

strncpy(attrValue, attrPtr, position-1);

回答by Matthew Flaschen

strchrwill usually be somewhat faster. Also, you need to check for the NUL terminator, which strchr will handle for you.

strchr通常会更快一些。此外,您需要检查 NUL 终止符,strchr 将为您处理。

char *quotPtr = strchr(attrPtr, qolon);
if(quotPtr == NULL)
{
  ... // Handle error
}
int position = quotPtr - attrPtr;
char* attrValue = (char*) malloc((position + 1) * sizeof(char));
memcpy(attrValue, attrPtr, position);
attrValue[position] = '
char qolon = '"';//character to search
char *found;
char *attrVal = NULL;

found = strchr(attrPtr, qolon);

if (found)
{
    size_t len = found - attrPtr;

    attrVal = malloc(len + 1);
    memcpy(attrVal, attrPtr, len);
    attrVal[len] = '
while (*(attrPtr + position++) != qolon);
'; }
';

I haven't tested, though.

不过我还没有测试。

EDIT: Fix off-by-one.

编辑:逐一修复。

回答by caf

C has a built-in function for searching for a character in a string - strchr(). strchr()returns a pointer to the found character, not the array position, so you have to subtract the pointer to the start of the string from the returned pointer to get that. You could rewrite your function as:

C 有一个用于在字符串中搜索字符的内置函数 - strchr()strchr()返回一个指向找到的字符的指针,而不是数组位置,因此您必须从返回的指针中减去指向字符串开头的指针才能得到它。您可以将函数重写为:

while (attrPtr[position] && attrPtr[position++] != qolon);

This may be faster than your original by a small constant factor; however, you aren't going to get an order-of-magnitude speedup. Searching for a character within an un-ordered string is fundamentally O(n) in the length of the string.

这可能比你原来的快一个小的常数因子;但是,您不会获得数量级的加速。在无序字符串中搜索字符基本上是字符串长度的 O(n)。

回答by Justin Frankel

Two important things:

两个重要的事情:

1) Always check for a NULL terminator when searching a string this way:

1) 以这种方式搜索字符串时,始终检查 NULL 终止符:

strncpy(attrValue, attrPtr, position-1);

should be:

应该:

char buf[512];
strncpy(buf,"",4096);

(if passed a string lacking your searched character, it could take a very long time as it scans all memory). Edit: I just noticed someone else posted this before, me, but oh well. I disagree, btw, strchr() is fine, but a simple loop that also checks for the terminator is fine (and often has advantages), too.

(如果传递的字符串缺少您搜索的字符,则扫描所有内存可能需要很长时间)。编辑:我刚刚注意到其他人之前发布了这个,我,但是哦。我不同意,顺便说一句, strchr() 很好,但是一个也检查终止符的简单循环也很好(并且通常有优势)。

2) BEWARE of strncpy()!

2) 当心 strncpy()!

##代码##

strlen(attrPtr)>=(position-1) so this will NOTnull terminate the string in attrValue, which could cause all kinds of problems (including incredible slowdown in code later on). As a related note, strncpy() is erm, uniquely designed, so if you do something like:

strlen(attrPtr)>=(position-1) 所以这不会空终止 attrValue 中的字符串,这可能会导致各种问题(包括稍后代码中令人难以置信的减速)。作为相关说明, strncpy() 是 erm,设计独特,因此如果您执行以下操作:

##代码##

You will be writing 4096 bytes of zeroes.

您将写入 4096 个字节的零。

Personally, I use lstrcpyn() on Win32, and on other platforms I have a simple implementation of it. It is much more useful for me.

就我个人而言,我在 Win32 上使用 lstrcpyn(),在其他平台上我有一个简单的实现。它对我有用得多。

回答by T.E.D.

The algorithm you posted doesn't properly handle the case where the character doesn't exist in the string. If that happens, it will just merilly march through memory until it either randomly happens to find a byte that matches your char, or you blow past your allocated memory and get a segfault. I suspect that is why it seems to be "taking too long" sometimes.

您发布的算法无法正确处理字符串中不存在字符的情况。如果发生这种情况,它只会在内存中愉快地前进,直到它随机碰巧找到与您的字符匹配的字节,或者您超出分配的内存并出现段错误。我怀疑这就是为什么有时似乎“花费太长时间”的原因。

In C, strings are usually terminated with a 0 (ascii nul, or '\0'). Alternatively, if you know the length of the string ahead of time, you can use that.

在 C 中,字符串通常以 0(ascii nul 或'\0')结尾。或者,如果您提前知道字符串的长度,则可以使用它。

Of course, there is a standard C library routine that does exactly this: strchr(). A wise programmer would use that rather than risk bugs by rolling their own.

当然,还有一个标准C库例程正是这样做的:strchr()。一个聪明的程序员会使用它而不是通过自己滚动来冒险。

回答by Naveen

It requires an O(n)algorithm to search for a character in the string. So you can't do much better than what your are already doing. Also, note that you are missing memset(attrValue, 0, position);, otherwise your string attrValuewill not be null terminated.

它需要一种O(n)算法来搜索字符串中的字符。所以你不能做得比你已经在做的更好。另外,请注意您缺少memset(attrValue, 0, position);,否则您的字符串attrValue不会以空字符结尾。