I have a GPS that is spitting out strings of data, might look something like this:
String myString = "99,500,,45,W,5";
I'm trying to write a function that will extract a term from the string and return it e.g. when term = 2 it will return a string 500.
The following code works:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
String myString = "99,500,,45,W,5";
//String altitude = stringTermFunc(myString,2); // HOW TO RETURN A STRING FROM A FUNCTION?????
//Serial.print(altitude);
int Cc = commaCountFunc(myString); // Count number of commas in String
// Create an Nx1 array with the index of each comma in the string
int myArray[Cc];
int count = 0;
for (int i = 0; i < myString.length(); i = i + 1) {
if (myString.charAt(i) == ',') {
myArray[count] = i;
Serial.print("Comma Index: ");
Serial.println(myArray[count]);
count = count + 1;
}
}
// Extract the n th term from the string where n=0 will be the first term
int n =0; // Choose a Term in string to extract
int m = n-1; // Index in myArray (excluding m = -1)
if (n == 0){
String myTerm = myString.substring(0,myArray[0]);
Serial.print(myTerm);
}
else{
String myTerm = myString.substring(myArray[m]+1,myArray[m+1]);
Serial.print(myTerm);
}
}
void loop() {
// put your main code here, to run repeatedly:
//NOTHING
}
// Functions
int commaCountFunc(String& myString){
// Function that counts the number of comma delimiters in a string
// String myString = "99,500,,45,W,5"; // Example String
int count = 0;
int i = myString.length();
for (int x = 0; x<i; x = x + 1){
if (myString.charAt(x) == ','){
//commaIndex[count] = myString.indexOf(',',x);
count = count + 1;
}
}
return count;
}
I'd now like to write it into a function that takes a comma spaced string, extracts the term you want as a string or char array. But I'm having problems with this.
Does anyone have any thoughts?
Thanks,
Chris