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

ArduinoArduino BoardsArduino IDEArduino Programming Language

The indexOf() function within Arduino scans a string from the beginning, and returns the first index of the specified substring within the string. The syntax is −

Syntax

myString.indexOf(substr)

where substr is the substring to search for. It can be of type character or string.

Optionally, you can provide a different starting point to begin the search from, in which case, the syntax is −

Syntax

myString.indexOf(substr, from)

where from is the index from where the search should start. This function returns the index of the first occurrence of the substring within the string, or -1, if no match is found.

Example

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.indexOf(substr1));
   Serial.println(s1.indexOf(substr2));
   Serial.println(s1.indexOf(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 index 1 was printed (counting starts from 0). In the second case, since no match was found, -1 was printed. In the third case, we told Arduino to start searching from index 3. Therefore, the next match was found at index 4, and that was printed.

raja
Published on 29-May-2021 13:14:36
Advertisements