Reputation: 39
I want to separate the whole name into only first and last name, but the name can be more than one. I wrote a code like this, but this code is only set to 2 names.
for (int i = 0; i < size; i++) {
char* first = strtok(temp[i].full, " ");
char* second = strtok(NULL, " ");
char* last = strtok(NULL, " ");
if (last == NULL) {
strcpy(data[i].name, first);
strcpy(data[i].surname, second);
}
else{
strcpy(data[i].name, first);
strcpy(data[i].secName, second);
strcpy(data[i].surname, last);
}
}
But the format I need is:
full name : jack joe woo
name: jack joe
surname: woo
or
full name : jack joe jes woo
name: jack joe jes
surname: woo
How can I get only the last word as a surname and the rest as a name?
Upvotes: 1
Views: 509
Reputation: 25116
Here is a solution which uses strtok
:
#include <stdio.h>
#include <string.h>
//Note that this function will modify the string,
//because that is the way that strtok behaves.
void print_names( char *full_name )
{
char *current, *next;
printf( "full name: %s\n", full_name );
current = strtok( full_name, " " );
printf( "first names:" );
while( (next = strtok( NULL, " " )) != NULL )
{
printf( " %s", current );
current = next;
}
printf( "\nlast name: %s\n", current );
}
int main( void )
{
//Note that the string we pass to the function must
//be writable, because the function uses strtok.
char test_string[] = "jack joe jes woo";
print_names( test_string );
}
This program has the following output:
full name: jack joe jes woo
first names: jack joe jes
last name: woo
However, using strtok
has several disadvantages:
Therefore, I have provided an alternate solution which does not use strtok
, but uses strrchr
instead:
#include <stdio.h>
#include <string.h>
void print_names( const char *full_name )
{
printf( "full name: %s\n", full_name );
char *p = strrchr( full_name, ' ' );
if ( p == NULL )
{
fprintf( stderr, "parse error\n" );
return;
}
printf( "first names: %.*s\n", (int)(p - full_name), full_name );
printf( "last name: %s\n", p + 1 );
}
int main( void )
{
//Note that we can now pass a read-only string
//string, because we are not using strtok anymore.
print_names( "jack joe jes woo" );
}
This program has exactly the same output as the other program.
Upvotes: 1
Reputation: 781721
Use strrchr()
to search for the last space character. Everything before that is the first name, everything after is the last name.
char *lname = strrchr(temp[i].full, ' ');
if (lname) {
*lname = '\0'; // replace space with null terminator
lname++; // point to the beginning of last name
strcpy(data[i].name, temp[i].full);
strcpy(data[i].surname, lname);
}
Upvotes: 2