Fix subStr related exceptions

This commit is contained in:
Theo Arends 2021-01-29 16:16:20 +01:00
parent 6084180419
commit ef59ad7d4f

View File

@ -253,8 +253,9 @@ uint32_t ChrCount(const char *str, const char *delim) {
}
// Function to return a substring defined by a delimiter at an index
char* subStr(char* dest, char* str, const char *delim, int index)
{
char* subStr(char* dest, char* str, const char *delim, int index) {
/*
// Exceptions on empty fields
char *act;
char *sub = nullptr;
char *ptr;
@ -266,6 +267,22 @@ char* subStr(char* dest, char* str, const char *delim, int index)
sub = strtok_r(act, delim, &ptr);
if (sub == nullptr) break;
}
return sub;
*/
uint32_t len = strlen(str) -1;
// Since strtok consumes the first arg, make a copy
strncpy(dest, str, len +2);
// Since strtok_r will exception if last char is delim change to space
if (strchr(delim, dest[len]) != nullptr) { dest[len] = ' '; }
char *ptr = dest;
char *sub;
int i = index;
while ( ptr && ((sub = strtok_r(ptr, delim, &ptr))) && (--i) ) {
// Serial.printf("%s|", sub);
}
// Serial.printf("%s|=\n|", sub);
sub = Trim(sub);
return sub;
}