Reputation: 476
I just want to find a special sub-string in another string and save it as another string. Here is the code:
char sub[13]={};
char *ptr = sub;
char src[100] = "SOME DATE HERE CBC: 2345,23, SOME OTHER DATA";
// |----------|
ptr = strstr(src,"CBC:");
strncpy(sub,ptr,sizeof(sub)-1);
Is this an efficient way or does a better method exist for this? Thanks.
Upvotes: 1
Views: 429
Reputation: 359
Unless this piece of code is in a critical path and it's the actual source of a performance bottleneck, then just stick to what you have. Default strstr
implementation should be quite adequate for the task.
You can squeeze some peanuts by pre-computing the end of src
, for example, so you could use memcmp
(an unconditional loop) instead of strncpy
(which has a conditional loop) when extracting the sub
. If you know beforehand the substring you are searching for, you can optimize around that too; especially if it's exactly 4 characters. And so on and so forth.
But if you are after these peanuts, you might be (much) better off by redoing the code to not extract sub
to begin with and use something like ranged strings to keep track of where it is in the source string.
Upvotes: 1
Reputation: 153358
Is this an efficient way or does a better method exist for this?
Pros:
Uses strstr()
which is likely more efficient and correct that coding your own search.
Cons:
Does not handle the case when strstr()
return NULL
resulting in undefined behavior (UB). @Paul Ogilvie
ptr = strstr(src,"CBC:");
// add test
if (ptr) {
// copy
} else {
// Handle not found, perhaps `sub[0] = '\0';`
}
char sub[13]={};
is not compliant C code. @pmg. A full initialization of the array is not needed - even though it is a common good practice.
Code does not quite fulfill "want to find a special sub-string in another string and save it as another string". Its more like "want to find a special sub-string in another string and save it and more as another string".
strncpy(sub,ptr,sizeof(sub)-1)
can unnecessarily mostly fill the array with null characters. This is inefficient when ptr
points to a string much less than sizeof(sub)
. Code could use strncat()
but that is tricky. See this good answer @AnT.
// alternative
char src[100] = "SOME DATE HERE CBC: 2345,23, SOME OTHER DATA";
char sub[13];
sub[0] = '\0';
const char *ptr = strstr(src, "CBC:");
if (ptr) {
strncat(sub, p, sizeof sub - 1);
}
Upvotes: 1