Home > Enterprise >  Separate a string with characters, spaces and integers into string and integer in C
Separate a string with characters, spaces and integers into string and integer in C

Time:01-28

I am looking for a way to separate a string into a string and integer at the last space in C

"121 212 27387" into "121 212" and 27387
"pur ple 16091" into "pur ple" and 16091
"98!=76 54321 22143" into "98!=76 54321" and 22143

the integer can be extracted with atoi(strrchr()), but I don't know how the string can be extracted, sscanf won't work, because it stops at the first space

CodePudding user response:

You just have to locate the last occurrence of the space. Assign a pointer to the address. From there you can convert the number to an integer and you can copy the string to a new variable.

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

int main() {
    char substring[32];
    char string[] = "121 212 27387";
    char *p = strrchr(string, ' ');
    size_t distance = p - &string[0];
    int num = atoi(p);
    
    strncpy(substring, string, distance);
    
    printf("num = %d\n", num);
    printf("distance = %d\n", distance);
    printf("substring = %s\n", substring);
    
    return 0;
}
  •  Tags:  
  • Related