如何获得给定字符串的子字符串?

时间:2018-12-30 07:52:51

标签: c ansi-c

我需要从给定的字符串中获取第一个实数(在,之后) 例如:

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);

我需要输入num-“ 3.444”

1 个答案:

答案 0 :(得分:1)

您应该使用已经可用的“字符串”函数,而不是编写自己的解析。像这样:

#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;
}
相关问题