如何获取给定字符串的子字符串?
How to get a substring of a given string?
我需要从给定的字符串中获取第一个实数(在 ,
之后)
例如:
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] = '[=10=]';
re_part = atof(r_part);
free(r_part);
我需要 num
为给定的数字 - “3.444”
您应该使用已经可用的 "string" 函数,而不是编写您自己的解析。类似于:
#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;
}
我需要从给定的字符串中获取第一个实数(在 ,
之后)
例如:
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] = '[=10=]';
re_part = atof(r_part);
free(r_part);
我需要 num
为给定的数字 - “3.444”
您应该使用已经可用的 "string" 函数,而不是编写您自己的解析。类似于:
#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;
}