Sitemap / Advertise

Information



Tags



Share

How to split strings in Arduino IDE to glean information as substrings

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

If you are looking for a job as Coder, visit Jooble.

While coding in Arduino IDE, you might think that if there is a simple way to split and scan strings to collect information, you would have completed the project earlier than estimated. However, there is no easy way to split a string as other programming languages offered already such as PHP and Java. In Arduino, in spite of the fact that it is intricate and incoherent as compared to other methods in other languages, by defining a delimiter and its index as a reference point to define the latter delimiter, you can create substrings emerged from strings in accordance with delimiter locations. I shall explain details on the source code below. The required Arduino functions:

indexOf()(1)

Locates a character or String within another String. By default, searches from the beginning of the String, but can also start from a given index, allowing for the locating of all instances of the character or String.

substring()(2)

Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.

Code

Define a delimiter to split the readString. I choose to use the percentage sign(%).

Detect the location of the first delimiter as a reference point by using the indexOf() function.

Depending on the first delimiter, get the next delimiter locations.

By using the substring() function, split the readString from one delimiter to the other.

Do not forget to add 1 to exclude the delimiter itself from the result.

void loop(){

String readString = "%Enter%your%string%here";

// Split the readString by a pre-defined delimiter in a simple way. '%'(percentage) is defined as the delimiter in this project.
int delimiter, delimiter_1, delimiter_2, delimiter_3;
delimiter = readString.indexOf("%");
delimiter_1 = readString.indexOf("%", delimiter + 1);
delimiter_2 = readString.indexOf("%", delimiter_1 +1);
delimiter_3 = readString.indexOf("%", delimiter_2 +1);

// Define variables to be executed on the code later by collecting information from the readString as substrings.
String first = readString.substring(delimiter + 1, delimiter_1);
String second = readString.substring(delimiter_1 + 1, delimiter_2);
String third = readString.substring(delimiter_2 + 1, delimiter_3);

}

References

(1) https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

(2) https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/substring/