【问题标题】:separating a string to a double array with seperators使用分隔符将字符串分隔为双精度数组
【发布时间】:2016-05-21 09:24:07
【问题描述】:

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

我尝试了多种选择,但都没有成功

我有一个给定的函数 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;

我们将不胜感激

【问题讨论】:

  • 给我们一个你想使用的字符串格式。它应该是您将传递给此函数的一种标准格式。我们是否应该考虑你总是传递“30% 40% 50%”这种字符串?
  • 是的!字符串之王总是这样,其中的元素数量也将作为 numOfgrades 给出。 @Mazhar

标签: c arrays string split


【解决方案1】:

检查一下。

#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;
}

【讨论】:

  • 很高兴听到它对@Beginner 有所帮助
【解决方案2】:

你可以像这样使用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 的零值。

【讨论】:

  • 这是一个很好的解决方案,但我得到了与以前相同的错误。 atof 行存在书写违规。我不明白为什么
  • 您是否将字符串传递给此函数,例如 ("60%20%40",3) ?然后它会显示一个错误。因为 strtok() 改变了你传递的字符串。因此,您不能将常量字符串传递给它。如果您要使用这种方法,您应该首先将字符串存储在字符数组中,例如 char[] ="60%20%40" 然后将其传递给您的函数
  • 或者您可以在函数中复制该字符串并对该字符串执行操作。 – 使用 strdup 编辑代码
  • 我不知道!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-03-15
  • 2010-12-07
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多