Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding character in string C language

Tags:

c

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: attrPtr is a char * which holds a reference to a string containing '"' character at far extent.

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);
like image 442
boom Avatar asked Jun 03 '10 04:06

boom


2 Answers

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

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] = '\0';

I haven't tested, though.

EDIT: Fix off-by-one.

like image 197
Matthew Flaschen Avatar answered Sep 22 '22 12:09

Matthew Flaschen


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:

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] = '\0';
}

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.

like image 26
caf Avatar answered Sep 24 '22 12:09

caf