Originally Posted by
Xender1
I know this msg has two strings (first name/last name each max 40 bytes), my question is how do I extract this out? I have allocated 2 other char arrays to be of size 40
You indicated above what the max size (length) of a first name or last name may be, however you did not specify what would be the minimum size (presumably a single character would suffice?). Anyhow, you shouldn't assume the last name begins at offset 41 unless the conjoined string is set up that way.
Is there any field separator between the first and last names? If so, then it may be possible to use strchr() to find that point in the string, thus giving you a reference point as to where one string ends and the next begins.
Maybe the following will give an idea:
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
const char* first_last = "Fred Flintstone";
const char* space = strchr(first_last, ' '); // assume space-character separator
const char* end = strchr(first_last, '\0'); // look for terminating null-character
#ifndef _GNU_SOURCE
char* first = malloc(space - first_last + 1);
char* last = malloc(end - space);
snprintf(first, space - first_last + 1, "%s", first_last);
snprintf(last, end - space + 1, "%s", space + 1);
#else
char* first = strndup(first_last, space - first_last);
char* last = strndup(space + 1, end - space);
#endif
printf("first name is: %s\n", first);
printf("last name is : %s\n", last);
free(first);
free(last);
return 0;
}
Bookmarks