Java indexOf Examples

Use indexOf to search for characters and strings. Call indexOf in while-loops.

IndexOf. A String possibly contains a matching value. With indexOf, we can search it, from the start, for a match. This works with char and String arguments.

When no value is found, indexOf will return -1. To search from the end of a string, please use lastIndexOf. With indexOf we search from start to end.lastIndexOf

An example. This program uses indexOf with character arguments. The 3 indexOf calls locate indexes of the chars b, d, and z (which is not found).

Part 1: We try to locate a char in a string. The letter "b" returns the index 1, which is returned.

Part 2: Here we store the index of "d" in an int named "d." We often store the result of indexOf in an int.

Part 3: Here we try to find a char that does not exist in the string. For "z," negative one is returned.

Java program that uses indexOf public class Program { public static void main(String[] args) { String line = "abcd"; // Part 1: locate char in string. int b = line.indexOf('b'); System.out.println(b); // Part 2: locate another char at different index. int d = line.indexOf('d'); System.out.println(d); // Part 3: not found, error code. int z = line.indexOf('z'); System.out.println(z); } } Output 1 3 -1

IndexOf, string. Finding a char within a String is useful. But finding a substring or multiple-character sequence is often more helpful. IndexOf (and lastIndexOf) supports this.

Also: We can pass a start index optionally to these methods to restrict our search field.

Java program that uses indexOf, string argument public class Program { public static void main(String[] args) { String line = "one two three"; // Get index of substring two. int index = line.indexOf("two"); System.out.println(index); } } Output 4

While-loop. We often use indexOf within a loop. Consider this program. It continues call indexOf as it advances the position. It finds all instances of the two-char string.While

Substring: When the 2-char string is found with indexOf, we print a substring of the remaining string.

Java program that uses indexOf, while-loop public class Program { public static void main(String[] args) { String data = "abcabcabc"; // Keep looping until -1 encountered. int pos = 0; while ((pos = data.indexOf("ab", pos)) != -1) { // Print position and the substring starting at it. System.out.println(pos); System.out.println(data.substring(pos)); pos++; } } } Output 0 abcabcabc 3 abcabc 6 abc

Null argument error. We must be careful with indexOf when we might have null Strings. If we pass it a null argument, it will throw a NullPointerException.
Java program that causes NullPointerException public class Program { public static void main(String[] args) { String data = "welcome"; int j = data.indexOf(null); // Cannot do this. System.out.println(j); } } Output Exception in thread "main" java.lang.NullPointerException at java.lang.String.indexOf(Unknown Source) at java.lang.String.indexOf(Unknown Source) at program.Program.main(

Contains. How can we search one String for another? With contains(), we pass in a String we want to find. The method returns true, if the String is found. It returns false if not.Boolean

Case: In my testing, the contains() method is case-sensitive. We can compare strings case-insensitively in many ways.

Also: We can use a custom char-searching method. Or we could change a program to completely avoid the problem.

Java program that uses contains public class Program { public static void main(String[] args) { String name = "socrates"; String value1 = "soc"; String value2 = "rate"; String value3 = "plato"; // The name contains this value. if (name.contains(value1)) { System.out.println(value1); } // The name also contains this value. if (name.contains(value2)) { System.out.println(value2); } // The name does not contain this value. if (!name.contains(value3)) { System.out.println("no: " + value3); } } } Output soc rate no: plato

Benchmark, indexOf. In this test, we find that a call to indexOf is faster than a for-loop with calls to charAt. When possible, indexOf is preferable to for-loops. It locates chars faster.

Version 1: This program searches the "input" string for the lowercase "m." This version uses indexOf.

Version 2: This code uses "for" and charAt. When the current character is the lowercase "m" it breaks out of the loop.


Result: It is faster to use indexOf in this benchmark. The loop could do more than one thing at once, which could help performance.

Java program that times indexOf, charAt public class Program { public static void main(String[] args) { String input = "abcdefghijklm"; long t1 = System.currentTimeMillis(); // Version 1: use indexOf to locate character. for (int i = 0; i < 10000000; i++) { int index = input.indexOf('m'); if (index < 0) { System.out.println("Error"); } } long t2 = System.currentTimeMillis(); // Version 2: use for, charAt to locate character. for (int i = 0; i < 10000000; i++) { int index = -1; for (int x = 0; x < input.length(); x++) { if (input.charAt(x) == 'm') { index = x; break; } } if (index < 0) { System.out.println("Error"); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 61 ms, indexOf 172 ms, for loop, charAt

Between, before, after. We can use indexOf and lastIndexOf to extract parts of strings relative to other substrings. Some reusable methods are helpful.Between, Before, After

String occurrence count. With indexOf and a while-loop we can count occurrences of one string within a source string. We introduce a countStringOccurrences method.String Occurrence

ArrayList. Strings have an indexOf method. But so do other classes like ArrayList. We use most indexOf methods in the same way: we test -1 to see if nothing was found.ArrayList: indexOf

With charAt, and a loop, we can search Strings without indexOf. But indexOf, a declarative method call, uses fewer statements. It may be (and often is) easier to read, debug and test.

Checking for negatives is a challenging part of using indexOf and lastIndexOf. We must handle -1 in a special case. Errors occur if we use an unchecked return value from indexOf.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to