Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java String Indexing
3.
The indexOf() function
4.
Overloaded indexOf() methods
4.1.
indexOf(int ch)
4.2.
indexOf(int ch, int fromIndex)
4.3.
indexOf(String substring)
4.4.
indexOf(String substring, int fromIndex)
5.
Frequently Asked Questions
5.1.
How to find all occurrences of a character or substring in Strings in Java?
5.2.
What is the main difference between Strings in Java, C and C++?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Java String indexOf()

Author Yashesvinee V
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A sequence of characters is known as a String. It is also an object whose value is enclosed within double quotes. Accessing and manipulating the characters are the two most common operations carried out on strings. These operations can be performed by using the functions/methods of the String class. One such function is the indexOf() method used to find the index of the first occurrence of a substring/character in the string.

Java String Indexing

In Java, every character in a String has a particular index associated with it. Similar to arrays, the first character is of index 0, followed by the next character with index 1. Thus the last character of the String will have an index that is one less than the length of the entire String.

For example, if the string is “hello world”, the index of ‘h’ is 0, and the index of ‘d’ is 10.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

The indexOf() function

The indexOf() helps find the location of the first occurrence of a character/substring in a string. It takes the substring to be located as its parameter and returns a positive integer value that gives the location in terms of an index. If the specified substring is not present in the String, it returns -1.

Using the indexOf() function can help determine the type of character at a position and count the number of its occurrences, if any. 

The indexOf() function can be used in four ways as it is an overloaded function. Let's learn each of them in detail with examples.

Overloaded indexOf() methods

indexOf(int ch)

Syntax:

int indexOf(char ch)

 

Parameters:

ch - the character to be searched.

It returns the index of the first occurrence of a character within the string’s limits. If not found, the function returns -1.

class Main 
{
  public static void main(String[] args) 
    {
    String s = "hello world";
    int length = s.length();
    System.out.println("Length of the string is: " + length);
    
    int result;

    result = s.indexOf('h');
    System.out.println("index of h: " + result); 

    result = s.indexOf('l');
    System.out.println("index of l(first occurance): " + result);

    result = s.indexOf('j');
    System.out.println("index of j:" + result);
       
    result = s.indexOf("");
    System.out.println("index of empty string: " + result);
  }
}

 

Output:

Length of the string is: 11
index of h: 0
index of l(first occurance): 2
index of j:-1
index of empty string: 0

indexOf(int ch, int fromIndex)

Syntax:

int indexOf(char ch, int index)

 

Parameters:

ch - a character.

index - The index to start the search from.

It returns the index of the first occurrence of a character starting from the given index in the string. If not found, the function returns -1.

class Main 
{
  public static void main(String[] args) 
  {
    String s = "hello world";
    int result;

    result = s.indexOf('h',4);
    System.out.println("index of h from index 4: " + result); 

    result = s.indexOf('l',4);
    System.out.println("index of l(first occurance) from index 4: " + result);

    }
}

 

Output:

index of h from index 4: -1
index of l(first occurance) from index 4: 9

indexOf(String substring)

Syntax:

int indexOf(String str)

 

Parameters:

str - a string.

It returns the index of the first occurrence of a substring within the string’s limits. If not found, the function returns -1.

class Main 
{
  public static void main(String[] args) 
  {
    String s = "hello world";
    int result;

    result = s.indexOf("llo");
    System.out.println("index of substring llo: " + result);
    
    result = s.indexOf("o w");
    System.out.println("index of substring o w: " + result);
    
    result = s.indexOf("helo");
    System.out.println("index of substring helo: " + result);

  }
}

 

Output:

index of substring llo: 2
index of substring o w: 4
index of substring helo: -1

indexOf(String substring, int fromIndex)

Syntax:

int indexOf(String str, int index)

 

Parameters:

index: the index to start the search from.

str: a string.

It returns the index of the first occurrence of a substring starting from the given index in the string. If not found, the function returns -1.

class Main 
{
  public static void main(String[] args) 
  {
    String s = "hello world";
    int result;

    result = s.indexOf("llo",4);
    System.out.println("index of substring llo from index 4: " + result);
    
    result = s.indexOf("rld",4);
    System.out.println("index of substring rld from index 4: " + result);
    
    result = s.indexOf("o w",4);
    System.out.println("index of substring o w from index 4: " + result);
    
    result = s.indexOf("helo",4);
    System.out.println("index of substring helo from index 4: " + result);

  }
}

 

Output:

index of substring llo from index 4: -1
index of substring rld from index 4: 8
index of substring o w from index 4: 4
index of substring helo from index 4: -1

Check out this article - Upcasting and Downcasting in Java

Must Read: Java System Out Println

Frequently Asked Questions

How to find all occurrences of a character or substring in Strings in Java?

The last occurrence of a substring /character can be found using the lastIndexOf() function. To find all the occurrences, we can use the indexOf() function in a loop and maintain a counter. On discovering the first occurrence, replace it with whitespace and increment the counter.

What is the main difference between Strings in Java, C and C++?

In C and C++, strings are terminated with null characters and are stored as character arrays. In Java, strings are not terminated with null characters. They are treated as objects.

Conclusion

In this article, we have extensively discussed the indexOf() function in Java. We briefly discussed indexing in Java Strings and then saw the different overloaded functions of the indexOf() function with examples. 

Feeling curious? Coding Ninjas has you covered. Check out our articles on the StringBuffer classStringBuilder class, and StringTokenizers in Java. Follow our Guided path for Programming in Java here.
Also check out - Substr C++

Recommended problems -

Explore our Library on Coding Ninjas Studio to gain knowledge on Data Structures and AlgorithmsMachine LearningDeep LearningCloud Computing and many more! Test your coding skills by solving our test series and participating in the contests hosted on Coding Ninjas Studio! 

Looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc.? Look at the problems, interview experiences, and interview bundle for placement preparations. Upvote our blogs if you find them insightful and engaging! Happy Coding!

Live masterclass