Monday, July 25, 2016

Filled Under: , ,

String indexOf() and lastIndexOf() Method

08.Strings library StringIndexOf
The String object indexOf() method gives you the ability to search for the first instance of a particular character value in a String. You can also look for the first instance of the character after a given offset. The lastIndexOf() method lets you do the same things from the end of a String.

  String stringOne = "<HTML><HEAD><BODY>";
  int firstClosingBracket = stringOne.indexOf('>');
In this case, firstClosingBracket equals 5, because the first character is at position 5 in the String (counting the first character as 0). If you want to get the second closing bracket, you can use the fact that you know the position of the first one, and search from firstClosingBracket + 1 as the offset, like so:

stringOne = "<HTML><HEAD><BODY>";
 int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );
The result would be 11, the position of the closing bracket for the HEAD tag.

If you want to search from the end of the String, you can use the lastIndexOf() method instead. This function returns the position of the last occurrence of a given character.

stringOne = "<HTML><HEAD><BODY>";
 int lastOpeningBracket = stringOne.lastIndexOf('<');
In this case, lastOpeningBracket equals 12, the position of the for the BODY tag. If you want the opening bracket for the HEAD tag, it would be atstringOne.lastIndexOf('<', lastOpeningBracket -1), or 6.


Step 1: What You Need?

Don't have components? Don't worry. Just click the component's name. 


Step 2: Build Your Circuit.

There is no circuit for this example, though your board must be connected to your computer via USB and the serial monitor window of the Arduino Software (IDE) should be open.

Step 3: Upload The Code.

1. Select the Arduino board type: Select Tools >> Board >> Select your correct Arduino board used.

2. Find the port number by accessing device manager on Windows. See the section Port (COM&LPT) and look for an open port named "Arduino Uno (COMxx)". If you are using a different board, you will find a name accordingly. What matters is the xx in COMxx part. In my case, it's COM3. So my port number is 3.

Select the right port: Tools >> Port >> Select the port number.

3. You can find this code in the example of Arduino IDE.
Select File >> Examples >> 08. Strings >> StringIndexOf

Click press the "upload" button (see the button with right arrow mark).

Download:





Unknown

Author & Editor

My Robot Education Sdn. Bhd. (Robotedu.my) was founded in 2015 as the first robotics education centre in Malaysia to provide Arduino-based robotics courses for youths. Our vision is to be able to provide robotics education to every youth in Malaysia.

0 comments:

Post a Comment

 

  • Copyright © Arduino Tutorial ™ is a registered trademark.
    Designed by Templateism. Hosted on Blogger Templates.