spranay
1
Hi ,
I am trying to separate a String with comma's in different variables
String coin1 = "bitcoin,2,0.01234";
String coin;
int decimal;
float holding;
where bitcoin is my coin , 2 is decimal point & 0.01234 is my holding.
I am trying with strtok() , but no good luck yet.
strtok() is used with C-strings (arrays of chars terminated by a zero). These are not Strings, which are objects of the String library
The String library has the indexOf() function that allows you to find teh position of sub Strings, such as a ","
The general advice on the forum is to use strings rather than Strings in the limited memory of most microcontrollers
spranay
3
Hi, Thanks for quick response.
What else i can use for my requirement ?
can you help ?
My advice would be to use C strings and to use strtok()
Then you must have seen examples of using strtok, right? Pretty sure they don’t have String
string - char array
vs.
String - object
I didn't do everything. I left some fun for you.
char coin1[] = "bitcoin,2,0.01234";
float holding;
float bonus = 100.1; // just for fun
char scan;
byte idx = 0;
byte comma1;
byte comma2;
//char field1[10];
//char field2[3];
char field3[10];
byte f3;
byte LL;
void setup()
{
Serial.begin(19200);
Serial.println("Go!");
}
void loop()
{
LL = strlen(coin1);
idx = 0;
findCommas ();
//Serial.println(comma1);
//Serial.println(comma2);
idx = comma2 + 1; // comma2 next place is field2=3
f3 = 0;
do
{
field3[f3] = coin1[idx];
f3 ++;
idx ++;
}while (idx < LL);
Serial.print("field3 = ");
Serial.println(field3);
holding = atof(field3); // string to float
holding = holding + bonus;
Serial.println(holding, 5);
delay(10000);
}
void findCommas ()
{
do
{
scan = coin1[idx];
idx ++;
}while(scan != ',');
comma1 = idx - 1;
idx ++;
do
{
scan = coin1[idx];
idx ++;
}while(scan != ',');
comma2 = idx - 1;
}
I used "c strings".
Might be better ways to do it, just a sort of demo.
c strings and atof() are key.
6v6gt
8
Can any of those fields in the comma separated list be empty, for example "bitcoin,,0.01234" ?