String.indexOf()

Description

Finds the position of the first occurrence of a character or a string inside another string. By default, searches from the beginning of the String, but can also start from a given index, allowing for the locating of all instances of the character or String.

Syntax

myString.indexOf(val)

myString.indexOf(val, from)

Parameter Values

  • myString: a variable of type String.
  • val: the value to search for. Allowed data types: char, String.
  • from: the index to start the search from.

Return Values

  • The index of val within the String, or -1 if not found.

Example Code

void setup() { Serial.begin(9600); String myString = "Arduino, ArduinoGetStarted.com"; int index = myString.indexOf("Arduino"); Serial.println(index); } void loop() { }

The result on Serial Monitor:

COM6
Send
0
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTES AND WARNINGS:

If the string is modified, it is highly recommended using String.reserve() to prevent the memory fragmentation issue

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES