Well, you could do it like this:
Code:
#include <stdio.h>
#include <string.h>
#define IDSIZE 3
int main(void)
{
char *str = "New York (500)";
char city[110];
char id[IDSIZE + 1];
char *p;
p = strchr(str, '(');
strncpy(city, str, p - str);
city[p - str] = '\0';
strncpy(id, p + 1, IDSIZE);
id[IDSIZE] = '\0';
printf("City: %s, Branch ID: %s\n", city, id);
return 0;
}
itsme@itsme:~/C$ ./cityid
City: New York , Branch ID: 500
But it makes some dangerous assumptions and the city string has a trailing space. It also isn't very strict on what the original string needs to look like. It limits the ID to 3 digits and doesn't even care if the string is in the format "city (id)".
This one is a lot better I think:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str = "New York (500)";
char city[110];
char id[110];
char *p, *q;
int tocopy;
if(!(p = strchr(str, '(')))
{
puts("String syntax validation failed -- Expected '('");
return 1;
}
// Get rid of space(s) between city name and ID field
for(q = p - 1;q >= str && *q == ' ';--q)
;
q++;
// Don't forget bounds checking
tocopy = q - str >= sizeof(city) ? sizeof(city) : q - str;
strncpy(city, str, tocopy);
city[tocopy] = '\0';
for(++p, q = id;q - id < sizeof(id) && *p != ')';++p, ++q)
*q = *p;
*q = '\0';
if(*p != ')')
{
puts("String syntax validation failed -- Expected ')'");
return 1;
}
printf("City: %s, Branch ID: %s\n", city, id);
return 0;
}
itsme@itsme:~/C$ ./cityid2
City: New York, Branch ID: 500