Problem:
So, I am reading a sensor and it is returning numeric flow data into a String that looks similar to this:
"21.77,22.44,22.51,23.62,23.6" // Data could be to the 1st or 2nd decimal place
What I need is to find a way to convert that long string (in this example 28 characters, but could be more or less!) into an Array with data type double, because I want to be able to add up all 5 indexes in the array and divide it by the number of indexes to get the average flow data.
What I've Done
I wrote out a road map for what I want to achieve
"21.77,22.44,22.51,23.62,23.6" - 1 String
"21.77","22.44","22.51","23.62","23.6" - 5 Strings in 1 Array (comas removed from Sting)
21.77,22.44,22.51,23.62,23.6 - Convert the 5 strings within the Array to the double data type
I know I need to loop through the characters within the string to find the ","'s and then convert all that into an Array, but I don't know where to start with this.
CodePudding user response:
You can use Split fonction (lot of language support it) to tokenize your string by comma separator and iter all token in loop to convert it to double. Algorithm example (in python) :
values = []
avg = 0
tokens = my_string.split(',')
for token in tokens:
value = float(token)
avg = value
values.append(value)
avg /= len(tokens)
print("data array=", values)
print("average =", avg)
If you use c langage see strtok
CodePudding user response:
Here you go, assuming c is wanted
char* str = _strdup("21.77,22.44,22.51,23.62,23.6");
char* buff = str;
double nums[10] = { 0 };
int i = 0;
for(int i = 0; i < 10; i )
{
char* numStr = strtok(buff, ",");
if (numStr == NULL)
break;
nums[i] = strtod(numStr, NULL);
buff = NULL;
}
free(str);
Note I did not allocate the output array dynamically, I just set an upper limit of 10