indexOf( ) and lastIndexOf( ) in Java

By: Hong Emailed: 1699 times Printed: 2203 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The String class provides two methods that allow you to search a string for a specified character or substring: • indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( )
Searches for the last occurrence of a character or substring.

These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or –1 on failure.

To search for the first occurrence of a character, use int indexOf(int ch)
To search for the last occurrence of a character, use int lastIndexOf(int ch)

Here, ch is the character being sought. To search for the first or last occurrence of a substring, use

int indexOf(String str)
int lastIndexOf(String str)

Here, str specifies the substring.
You can specify a starting point for the search using these forms:

int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of Strings:

// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) { String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}

Here is the output of this program:
Now is the time for all good men to come to the aid of their country.

indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(12)


1. View Comment

Hi its good for the learners and thosse who forgotten the concepts.
Thanks
-Gaffar--


View Tutorial          By: Md.Abdul Gaffar at 2008-01-12 06:00:14
2. View Comment

http://www.java-samples.com/showtutorial.php?tutorialid=225

Is that result for indexOf(t) is 8 for the above string?


View Tutorial          By: Prab at 2009-04-13 11:54:17
3. View Comment

so what about, if i need to remove these letters for example

xR-MxR-MHelloxR-M - String to remove R-M
Hello

and remove all the R-M's and Hellos

is there a way that this could be demonstrated using indexOf()?

Thanks


View Tutorial          By: need Help at 2009-11-12 08:40:31
4. View Comment

@Prab, no its 7 since it starts the counting at 0 rather than 1.

View Tutorial          By: Shadowfaux at 2009-11-21 15:22:49
5. View Comment

To "need help":

String str = "xR-MxR-MHelloxR-M";
for (String r : new String[] {"R-M", "Hello"})
{
str.replaceAll(r);
}


View Tutorial          By: alex at 2010-05-13 09:57:25
6. View Comment

To "need help":

String str = "xR-MxR-MHelloxR-M";
System.out.println(str.substring(str.lastIndexOf("M", 15)+1, str.lastIndexOf("x")));

;-)


View Tutorial          By: Mike at 2010-10-14 20:09:31
7. View Comment

what's the purpose of indexOf('t',10)

View Tutorial          By: pevi at 2011-02-22 04:23:20
8. View Comment

ASNWERING: what's the purpose of indexOf('t',10) ?

The purpose is to look for the index of the character 't' STARTING at index 10;

For instance:
String str = "hello world";
//Let's say you wanted to find the index of the second 'o'.
//You say:
System.out.println(str.indexOf('o',5));
//This searches the string for 'o' starting immediately after
// first 'o'. (Remember, Strings are simply arrays, and their
// indexes start out at 0.


View Tutorial          By: Kyle at 2012-03-22 09:17:04
9. View Comment

import java.io.*;
class lastindexof
{
public static void main(String argv[]) throws IOException
{
String mystr;
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the string");
mystr=bf.readLine();
System.out.println(" character at position is=" +mystr.lastIndexOf());
}
}

why this program always showing me cannot find symbol error


View Tutorial          By: arya at 2012-11-07 08:37:59
10. View Comment

its cool, you've cleared me.

View Tutorial          By: zealous at 2013-09-10 17:40:26
11. View Comment

u can try this out it will satisify u:)
import java.io.*;
public class lastindexof
{
public static void main(String[] args) throws IOException
{
String mystr;
int cou=0;
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the string");
mystr=bf.readLine();
System.out.println("enter the string ");
String st=bf.readLine();
for(int i=0;i<mystr.length()-1;i++)
{
if(mystr.indexOf(st)!=-1)
cou++;
}
System.out.println(" character at position is=" +mystr.indexOf(st));
System.out.println(cou);;
}
}


View Tutorial          By: vallabh at 2014-10-04 17:44:18
12. View Comment

can anybody suggest me to write a java prog. to keep dot before every consonant?

View Tutorial          By: Giri at 2015-03-23 17:56:58

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Hong
How to use ArrayList in Java
Using totalMemory( ) and freeMemory( ) in Java
indexOf( ) and lastIndexOf( ) in Java
Extract characters in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Recursion in java
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Read from a COM port using Java program
The Basic Structure of a Simple Java program
Multidimensional or arrays of arrays in Java
InetAddress Example program in Java
Sample Java program shows how to write to COM port using Java.
concat(), replace(), and trim() Strings in Java
Integer: byte, short, int, and long data types in Java
Text to Speech conversion program in Java
Connect to a password protected URL from Java program
Count number of vowels, consonants and digits in a String in Java
Most Emailed Articles (in Java)
Read from a COM port using Java program
How to use ArrayList in Java
Data Types in Java
Write to a COM port using Java program
How to access instance from an inner class and accessing outer class variables in java
History of Java
Method Overloading (function overloading) in Java
Sample program to demonstrate the use of ActionListener
Tomcat and httpd configured in port 8080 and 80
Save/Write/Read image file from/to a database using Java program
Java program for changeable wrapper class
Report Sections in JasperReports
Using jar utility in Java - A jar tutorial
FilenameFilter - sample program in Java
Observable class and the sample program in Java