Skip to content

Instantly share code, notes, and snippets.

@smching
Last active March 6, 2024 05:59
Show Gist options
  • Save smching/fc464447501cf6f195ea7912778b6542 to your computer and use it in GitHub Desktop.
Save smching/fc464447501cf6f195ea7912778b6542 to your computer and use it in GitHub Desktop.
Split comma or any other character delimited string into an array
/*
Arduino sketch: Split comma or any other character delimited string into an array
by SM Ching (http://ediy.com.my)
*/
#define MAX_WORLD_COUNT 5
#define MIN_WORLD_COUNT 2
char *Words[MAX_WORLD_COUNT];
char *StringToParse;
void setup() {
Serial.begin(9600);
//Serial.println("Split string example.");
}
void loop() {
byte word_count;
//comma delimited
StringToParse = "One_1,Two_2,Theree_3,Four_4";
word_count = split_message(StringToParse);
if (word_count >= MIN_WORLD_COUNT) {
print_message(word_count);
}
//space delimited
StringToParse = "1_One 2_Two 3_Theree 4_Four 5_Five";
word_count = split_message(StringToParse);
if (word_count >= MIN_WORLD_COUNT) {
print_message(word_count);
}
//mix characters (comma & space) delimited
//will not output Six & Seven since MAX_WORLD_COUN=5
StringToParse = "One,Two,Theree Four Five Six Seven";
word_count = split_message(StringToParse);
if (word_count >= MIN_WORLD_COUNT) {
print_message(word_count);
}
}
////////// ////////// ////////// ////////// ////////// ////////// //////////
// Split string into individual words and store each word into an array
// this function return word_count (number of words)
////////// ////////// ////////// ////////// ////////// ////////// //////////
byte split_message(char* str) {
byte word_count = 0; //number of words
char * item = strtok (str, " ,"); //getting first word (uses space & comma as delimeter)
while (item != NULL) {
if (word_count >= MAX_WORLD_COUNT) {
break;
}
Words[word_count] = item;
item = strtok (NULL, " ,"); //getting subsequence word
word_count++;
}
return word_count;
}
////////// ////////// ////////// ////////// ////////// ////////// //////////
// Send array over serial
////////// ////////// ////////// ////////// ////////// ////////// //////////
void print_message(byte word_count) {
//if (word_count >= MIN_WORLD_COUNT) {
//Serial.print("Word count : "); Serial.println(word_count);
for (byte sms_block = 0; sms_block < word_count; sms_block++) {
Serial.print("Word "); Serial.print(sms_block + 1); Serial.print(" : ");
Serial.println(Words[sms_block]);
}
Serial.println("--------------------");
//}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment