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);
}