Search code examples
cansi-c

How to get a substring of a given string?


I need to get the first real number from a given string(after a ,) for example:

char *line = "The num is, 3.444 bnmbnm";
//get_num returns the length of the number staring from index i
if(num_length = get_num(line, i))
  {
    printf("\n Error : Invalid parameter - not a number \n");
    return;
``}

help = (char *)malloc(num_length + 1);
if(help == NULL){
    printf("\n |*An error accoured : Failed to allocate memory*| \n");
    exit(0);
}
r_part = help;
memcpy(r_part, &line[i], num_length);
r_part[num_length] = '\0';
re_part = atof(r_part);
free(r_part);

I need num to be the given number - "3.444"


Solution

  • You should use the "string" functions already available instead of writing your own parsing. Something like:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char *line = "The num is, 3.444 bnmbnm";
        char* p = strchr(line, ',');               // Find the first comma
        if (p)
        {
            float f;
            if (sscanf(p+1, "%f", &f) ==1)     // Try to read a float starting after the comma (i.e. the +1)
            {
                printf("Found %f\n", f);
            }
            else
            {
                printf("No float after comma\n");
            }
        }
        else
        {
            printf("No comma\n");
        }
        return 0;
    }