Find if a substring exists within a string in Arduino


In order to check if a specific substring exists within a string in Arduino, the indexOf() function can be used. This returns the index of the first occurrence of the character or a string that you are searching for within another string. In case the character or string does not exist within the given string, the function returns -1.

Example implementations are given in the code below −

Example

void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1.indexOf('e'));
   Serial.println(s1.indexOf("Wor"));
   Serial.println(s1.indexOf('z'));
   Serial.println(s1.indexOf("Wer"));
}
void loop() {
   // put your main code here, to run repeatedly:
   
}

The Serial Monitor output is given below −

Output

As you can see, for the first two cases, the index is returned correctly (the counting starts from 0, thus 'H' has index 0, 'e' has index 1 and so on). "Wor" starts from index 6. For the last two cases, the searched character/string are not found in s1, and therefore, -1 is returned.

In case you wish to start the search from an offset, you can provide the second argument to the function, specifying the index from which the search should start.

See the below code −

Example

void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1.indexOf('o'));
   Serial.println(s1.indexOf('o',5));
}
void loop() {
   // put your main code here, to run repeatedly:
   
}

The Serial Monitor output is −

Output

As you can see, at the first step, the location of 'o' in Hello is returned (index 4). Later, when we specified that search should start from index 5, the location of 'o' in World is returned (index 7 of "Hello World").

Updated on: 23-Mar-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements