- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the first occurrence of a substring within a string in Arduino
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.