5

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"

chuckfinley
  • 2,577
  • 10
  • 32
  • 42

3 Answers3

9

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.

Kninnug
  • 7,992
  • 1
  • 30
  • 42
  • Why does this page say that it returns the first occurrence, rather than the last one? http://www.tutorialspoint.com/ansi_c/c_strchr.htm – chuckfinley Oct 28 '13 at 16:00
  • You missed the additional `r` – drahnr Oct 28 '13 at 16:02
  • 1
    "Finds the **last** occurrence of ch (after conversion to char) in the byte string pointed to by str." it says for me... Are you sure you're not on the page for `strchr`? – Kninnug Oct 28 '13 at 16:02
1

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;
  }
} 
twalberg
  • 59,951
  • 11
  • 89
  • 84
0

You can use strtok as follows

char str[] ="www.google.com";
  char *token;
  token = strtok (str,".");
  char *lastToken ;
  while (token != NULL)
  {
    lastToken = token ;
    token = strtok (NULL, ".");
  }
  printf("last token - %s",lastToken); 
Subbu
  • 2,063
  • 4
  • 29
  • 42