

Finally, we print out a message to the console, which states, “Strawberry appears at the index position “. Next, we use the indexOf() method to find where the substring Strawberry starts in the fruits string. This variable stores the list of the top-five most popular fruits stored last month. Then, we define a Java variable called fruits.
#Java substring indexof code
We define a class called FindStrawberry which stores the code for our procedure. Strawberry appears at the index position 11. ("Strawberry appears at the index position " + strawberry + ".") Int strawberry = fruits.indexOf("Strawberry") String fruits = "Apple Pear Strawberry Grape Mango" This example returns the index within this string at which the string begins: Here’s an example that searches for the Java string Strawberry in our list of fruits. To accomplish this task, we could use the indexOf() method. We know that Strawberry was the third-most-popular fruit, but we want to know at what position it is stored in our list of fruits. Suppose we are operating a fruit stand, and we have a string that contains the top-five most popular fruits sold last month. Let’s walk through an example to illustrate the indexOf() method in Java and how it finds an occurrence of a specified character.

substring is the character or substring whose start index position you want to find (required).The indexOf() method takes in two parameters: String_name.indexOf(substring, start_char) The syntax of the indexOf() method is as follows:

If the character or phrase does not occur in the string, indexOf() returns -1. The Java string indexOf() method retrieves the index value associated with a particular character or substring in a string.
#Java substring indexof how to
This tutorial will explore how to use the indexOf() method in Java, with reference to examples. indexOf() returns the index of a particular character or substring in a string. That’s where the indexOf() Java method comes in. One of your tasks may be to find where Mango appears in a list of fruits formatted as a string. Get Your Coding Bootcamp Sponsored by Your Employerīy continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunitiesįrom Career Karma by telephone, text message, and email.įor instance, suppose you are writing an inventory program for a fruit stand.Education Stipends for Coding Bootcamps.Best Coding Bootcamp Scholarships and Grants.Ultimate Guide to Coding Bootcamp Loans.What Is a Coding Bootcamp Job Guarantee?.Best Free Bootcamps and Coding Training.Best Online Coding Bootcamps and Courses.
