Parsing an array of chars
Let's say I have "game.abc" as a string (array of chars) and I want to get the chars that are before the dot. What you would deem to be the most efficient way to do this in C?
Is a "while until . copy char to char" the way to go or is开发者_JAVA技巧 there any other way?
I hope this question can help others also.
Thanks!
you can also use strchr()
followed by strncpy()
to find first instance of '.' in your string and then copy all characters before it to another string
It depends on what you're trying to optimize for. If for readability an ease of understanding/maintaining, then binW's suggestion is correct.
If you're chasing cycles and only want to visit each character of the input once, then it's better to do the two operations (searching for the dot and copying) in parallel as you suggest by doing them both in the same loop.
Note that the latter smells very much of premature optimization though.
Depending on EXACTLY what you are trying to achieve, parsing the string character by character yourself may be the most efficient in terms of processing speed. Otherwise the standard string library functions are probably the way to go as suggested in the other answers.
Most efficient copy from buffer to buffer would be:
char *in_ptr = in_string;
char *out_ptr = out_buffer;
while(*in_ptr != '.')
{
*out_ptr = *in_ptr;
in_ptr++;
out_ptr++;
}
*out_ptr = '\0';
However this risks buffer overflows.
Most efficient copy to allocated memory would probably be:
char *in_ptr = in_string;
while(*in_ptr != '.') in_ptr++;
out_string = (char *)malloc(in_ptr - in_string + 1);
memcpy(out_string, in_string, (in_ptr - in_string));
out_string[in_ptr - in_string] = '\0';
I hope my maths is correct there. It should be. You may, depending on compiler, get a slight optimisation by assigning (in_ptr - in_string) to another variable so it only gets calculated once. This second solution is almost identical to calling strchr() then memcpy(). I recommend memcpy as it saves having to replace the '.' with a null terminator, replace it afterwards, and copying the null terminator from one string to the other.
As unwind's answer (which arrived while I was writing this) all this is probably unnecessary optimisation. But nice to be aware of.
You can use strtok() to tokenise string .
#include <stdio.h>
main()
{
char str[]="games.abc";
char *tmp,*tmp1;
tmp = strtok(str,".");
printf("tmp %s\n",tmp);
tmp1 = strtok(NULL,"\0");
printf("tmp1 %s\n",tmp1);
}
Output
./tmp1
tmp games
tmp1 abc
精彩评论