0

I am trying to extract the city from the following string;

Kmart, 200 Irwin Ne, Fort Walton Beach FL

The code I made goes through the string and I can extract this;

Fort Walton Beach FL

However, I do not understand how to effectively extract the city. I can extract the state using strlen but that is not working for the city.

void getCity(char strCity[], const char strLine[])
{
   char newLine[MAX_CHARS_PER_LINE+1];
   char newCity[MAX_CHARS_PER_LINE+1];

   strcpy(newLine, strLine);
   char* token = strtok(newLine, ",");

   if(token != NULL)
   {
     token = strtok(NULL,",");
     token = strtok(NULL, ",");
   } 
   strcpy(newCity, token);
   strcpy(strCity, token);
thn
  • 3
  • 3
  • 1
    If the state code is always two letters, you can simply check for a space before those two letters, zap the space into a null, and what's left is the city name. Beware short strings (erroneous data). Your final `strcpy()` statements copy the same information to two local variables — that probably isn't what you wanted. – Jonathan Leffler Jul 12 '19 at 21:46

1 Answers1

2

Take the string you have ("Fort Walton Beach FL") and use a reverse search for the "first" (which is really the last) space. Use e.g. strrchr to do it.

Then change that space to the string terminator '\0' and the string will become "Fort Walton Beach".

Increase the pointer to the (former) space and you have a pointer to the first character of the state, if you need that as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks. But really quick, how would change the space to the string terminator? I'm a bit confused on that – thn Jul 12 '19 at 22:14
  • 1
    Literally assign it `char *c = strrchr(test, ' '); if(c) *c = '\0'; else . . .`. – Neil Jul 13 '19 at 00:01