Can anyone help me with string operations?
I have a CSV string that I would like to assign string variables to different values within the string
such as:
string str1 = CSVstring[0];
string str2 = CSVstring[1];
I haven't played around with strings before and there must be some sort of string
operation commands available?
What is the best way to do this?
THANKS!
You may want to have a look at the text parser library.
Example:
#include <textparser.h>
TextParser parser(", "); // Delimiter is a comma followed by a space.
If all fields are of the same type, we can use an array.
int a[5];
parser.parseLine("1, 2, 3, 4, 5", a);
// `a` now contains 1, 2, 3, 4 and 5.
If the fields have different types, we can use multiple variables.
char a[4];
int b;
double c;
parser.parseLine("one, 2, 3.4", a, b, c);
// `a` now contains "one", `b` contains 2 and `c` contains 3.4.
In your case, instead of providing a string constant, as is done in the examples above, you can provide CSVstring.c_str()
.
Do you mean "char *" when you say 'string' or do you mean "String" when you say 'string'? The coding is different for each.
gcjr
4
consider
char s [80];
// -----------------------------------------------------------------------------
#define MaxTok 10
char *toks [MaxTok];
int vals [MaxTok];
int
tokenize (
char *s,
const char *sep )
{
unsigned n = 0;
toks [n] = strtok (s, sep);
vals [n] = atoi (toks [n]);
for (n = 1; (toks [n] = strtok (NULL, sep)); n++)
vals [n] = atoi (toks [n]);
return n;
}
// -----------------------------------------------------------------------------
void dispToks (
char * toks [])
{
char s [40];
for (unsigned n = 0; toks [n]; n++) {
sprintf (s, " %6d %s", vals [n], toks [n]);
Serial.println (s);
}
}
// -----------------------------------------------------------------------------
void loop ()
{
if (Serial.available ()) {
int n = Serial. readBytesUntil ('\n', s, sizeof(s)-1);
s [n] = 0; // terminate string
tokenize (s, ",");
dispToks (toks);
}
}
// -----------------------------------------------------------------------------
void setup ()
{
Serial.begin (9600);
}
system
Closed
5
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.