使用分隔符将字符串分隔为双数组

时间:2016-05-21 09:24:07

标签: c arrays string split

我想创建一个从特定字符串返回双精度数组的函数。

我尝试过多种选择而没有成功

我有一个给定的函数createWeightsArray,我需要填充它。 还将给出numofgrades,这是有帮助的

字符串将类似于:" 30%40%50%"我需要一个双数组{0.3,0.4,0.5}

这是我最近的尝试:

double* createWeightsArray(char* str, int numOfGrades) {
double *gradesweight;
gradesweight = (double*)malloc(numOfGrades * sizeof(double));
int i = 0, n = 0;
while (*str != '\0') {
    while (strchr("%", *str)) ++str;
    if (*str == '\0') break;
    *(gradesweight + n) = (atof(str) / 100);
    n++;
    str = strstr(str, "% ");
    if (str == NULL) break;
    *str = '\0';
    ++str;
}
return gradesweight;

将提供任何帮助

2 个答案:

答案 0 :(得分:0)

您可以像这样使用strtok

double* createWeightsArray(char* str1, int numOfGrades) {
double *gradesweight;
char *str =strdup(str1);
gradesweight = (double*)malloc(numOfGrades * sizeof(double));
int i = 0;

*gradesweight = atof(strtok(str,"%"))/100;
i++;
while (--numOfGrades) {
    *(gradesweight+i) = atof(strtok(NULL,"%") )/100;
    i++;
}
return gradesweight;
}

如果您确定提供了numOfGrades,那么在调用此函数之前,请检查numberOfGrades的零值。

答案 1 :(得分:0)

检查出来。

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

double* str2double(char *string, int length)
{
 int index = 0;
 const char delimitor[2] = "% "; /* Delimintor, used the break the string */
 char *token;
 double *array = malloc(sizeof(double) * length);

 if (array == NULL){
     fprintf(stderr, "Failed to allocate memory \n");
     return NULL;
 }

 /* get the first token */
 token = strtok(string, delimitor);

 /* walk through other tokens */
 for( index=0; token != NULL && index < length ; index++)
 {
     array[index] = strtod(token, &token) / 100;
     token = strtok(NULL, delimitor);
 }
 return array;   
}

int main()
{
   char str[] = "30% 40% 80% 60%";
   double *ptr = str2double(str, 4); 

   if (ptr != NULL) {
   for (int i = 0; i < 4; i++)
    printf( "%f\n", ptr[i]);
   }

   return 0;
}