Here is Arduino method to split a String as answer to the question "How to split a string in substring?" declared as a duplicate of the present question.
The objective of the solution is to parse a series of GPS positions logged into a SD card file. Instead of having a String received from Serial
, the String is read from file.
The function is StringSplit()
parse a String sLine = "1.12345,4.56789,hello"
to 3 Strings sParams[0]="1.12345"
, sParams[1]="4.56789"
& sParams[2]="hello"
.
String sInput
: the input lines to be parsed,
char cDelim
: the delimiter character between parameters,
String sParams[]
: the output array of parameters,
int iMaxParams
: the maximum number of parameters,
- Output
int
: the number of parsed parameters,
The function is based on String::indexOf()
and String::substring()
:
int StringSplit(String sInput, char cDelim, String sParams[], int iMaxParams)
{
int iParamCount = 0;
int iPosDelim, iPosStart = 0;
do {
// Searching the delimiter using indexOf()
iPosDelim = sInput.indexOf(cDelim,iPosStart);
if (iPosDelim > (iPosStart+1)) {
// Adding a new parameter using substring()
sParams[iParamCount] = sInput.substring(iPosStart,iPosDelim-1);
iParamCount++;
// Checking the number of parameters
if (iParamCount >= iMaxParams) {
return (iParamCount);
}
iPosStart = iPosDelim + 1;
}
} while (iPosDelim >= 0);
if (iParamCount < iMaxParams) {
// Adding the last parameter as the end of the line
sParams[iParamCount] = sInput.substring(iPosStart);
iParamCount++;
}
return (iParamCount);
}
And the usage is really simple:
String sParams[3];
int iCount, i;
String sLine;
// reading the line from file
sLine = readLine();
// parse only if exists
if (sLine.length() > 0) {
// parse the line
iCount = StringSplit(sLine,',',sParams,3);
// print the extracted paramters
for(i=0;i<iCount;i++) {
Serial.print(sParams[i]);
}
Serial.println("");
}