Table of Contents
In this post, we will see how to find character in String in java.
How to Find Character in String in Java
There are multiple ways to find char in String in java
1. Using indexOf() Method to Find Character in String in Java
indexOf() method is used to find index of substring present in String. It returns 1 if character is present in String else returns -1.
1 2 3 |
public int indexOf(int ch) |
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class FindCharacterInStringJava { public static void main(String[] args) { String str = "Java2blog"; int indexOfA = str.indexOf('a'); System.out.println("Index of a in String Java2blog is: "+indexOfA); } } |
Output:
In case, you want to find character in String after nth index, then you can pass fromIndex
to indexOf method.
1 2 3 4 |
int indexOfA = str.indexOf('a',3); // Output : 5 |
2. Using lastIndexOf() Method to Find Char in String in Java
lastIndexOf() method is used to find last index of substring present in String. It returns 1 if character is present in String else returns -1. This method scans String from end and returns as soon as it finds the character.
1 2 3 |
public int lastIndexOf(int ch) |
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class FindCharacterInStringJava { public static void main(String[] args) { String str = "Java2blog"; int indexOfA = str.lastIndexOf('a'); System.out.println("Index of a in String Java2blog is: "+indexOfA); } } |
Output:
Find Character at Index in String in Java
Using String’s charAt() method, you can find character at index in String in java.
1 2 3 |
public char charAt(int index) |
Let’s see with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class FindCharacterInStringJava { public static void main(String[] args) { String str = "Java2blog"; char charAtIndex5 = str.charAt(5); System.out.println("Character at index 5 in String Java2blog is: "+charAtIndex5); } } |
Output:
Further reading:
how Do I Find Word in String in Java?
You can use indexOf()
method to find word in String in java. You need to pass word to indexOf()
method and it will return the index of word in the String.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class FindWordInStringMain { public static void main(String[] args) { String str = "Java2blog"; int indexOfA = str.indexOf("blog"); System.out.println("Index of blog in String Java2blog is: "+indexOfA); } } |
Output:
That’s all about how to find character in String in java.