Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving last set of input values from a char pointer

I have a few set of values in a single char* variable such as this:

char* a1 = "1234 4567 789";
char* a2 = "123 445";

They are separated by white space.

I am trying to retrieve the last set of value such as 789 and 445 from the char*, but I am not too sure how to do this.

I am currently doing this:

trimmed[strchr(trimmed, ' ') - trimmed] = '\0';

This only nets me the second set of value which doesn't work if there are more than 2 inputs.

Is there a good way to extract the final set of value irregardless whether if there is 1 or 3 inputs?

like image 530
Bocky Avatar asked Dec 01 '25 23:12

Bocky


1 Answers

You can write a corresponding function manually. For example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char * extract( const char *s, size_t n )
{
    if ( n == 0 ) return NULL;

    while ( n != 0 && isspace( ( unsigned char )s[n-1] ) ) --n;
    while ( n != 0 && isdigit( ( unsigned char )s[n-1] ) ) --n;

    return ( char * )( isdigit( ( unsigned char )s[n] ) ? &s[n] : NULL );
}

int main( void ) 
{
    char *s1 = "1234 4567 789";
    char *s2 = "123 445";

    char *p1 = extract( s1, strlen( s1 ) );

    while ( p1 )
    {
        printf( "%d ", atoi( p1 ) );
        p1 = extract( s1, p1 - s1 );
    }        
    printf( "\n" );

    p1 = extract( s2, strlen( s2 ) );

    while ( p1 )
    {
        printf( "%d ", atoi( p1 ) );
        p1 = extract( s2, p1 - s2 );
    }        
    printf( "\n" );
}    

The program output is

789 4567 1234 
445 123 

Take into account that you may not apply standard function strtok to string literals as it is suggested in some answers here.:)

like image 100
Vlad from Moscow Avatar answered Dec 03 '25 13:12

Vlad from Moscow