What is the most effective way to split a string and select the last element?
i.e. we have a string "www.google.com"
i would like to split this string where a "." occurs and select the last element which would be "com"
You can use strrchr
:
const char * tld = strrchr("www.google.com", '.');
// tld now points to ".com"
don't forget to check for NULL
in case a dot cannot be found. Also note that it doesn't return a new string, just a pointer to the last occuring '.'
in the original string.
I think I would personally do something like this, and skip using any of the functions (although some versions of strrchr
may actually work this way, I don't think they're necessarily guaranteed to):
char *findlast(char *str)
{ char *c = str, p = NULL; // assuming str is your input string
while (*c)
{ if (*c == '.')
p = c;
++c;
}
if (p)
{ // p points to the last occurrence of '.'
if (*(p+1)) // '.' is not last character
return p+1
else
// not sure what you want here - p+1 points to NULL and would be semantically
// correct, but basically returns a 0-length string; return NULL might be better
// for some use cases...
}
else
{ // p is NULL, meaning '.' did not exist in str
return p;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With