Get the last occurrence of a substring within a string in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Just like indexOf() helps identify the first occurrence of a substring within a string, the lastIndexOf() function helps identify the last occurrence. This is because lastIndexOf() performs backward search, while indexOf() performs forward search.



Where substr is the substring to search for in myString. It can be a character or a string.

Just like indexOf(), this function also accepts an optional from argument, in case you want the backward search to begin from a specific index. The syntax in that case is −


myString.lastIndexOf(substr, from)

Just like indexOf(), this function either returns the last index of the substring within the string, or it returns -1 if no match is found.


The following example code illustrates all of these points −

void setup() {
   // put your setup code here, to run once:
   String s1 = "Mississippi";
   String substr1 = "is";
   String substr2 = "os";
   Serial.println(s1.lastIndexOf(substr1, 3));
void loop() {
   // put your main code here, to run repeatedly:


The Serial Monitor Output is shown below −

As you can see, in the first case, the last index of the substring is returned (indexing starts with 0). In the second case, since no match was found, -1 was returned. In the third case, since we asked Arduino to start the backward scan from index 3, the next match, the index of the next match was returned.

Published on 29-May-2021 13:06:15