Get Last Occurrence of a Substring in Arduino



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.

syntax

myString.lastIndexOf(substr)

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 −

Syntax

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.

Example

The following example code illustrates all of these points −

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

Output

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.

Updated on: 2021-05-29T13:28:49+05:30

780 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements