Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: split a string and select last element [duplicate]

Tags:

c

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"

like image 933
chuckfinley Avatar asked Feb 14 '23 20:02

chuckfinley


2 Answers

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.

like image 104
Kninnug Avatar answered Feb 28 '23 19:02

Kninnug


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;
  }
} 
like image 32
twalberg Avatar answered Feb 28 '23 21:02

twalberg