Find Character in String in Java

Find character in String in java

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.

Let’s see with the help of example:

Output:

Index of a in String Java2blog is: 1

In case, you want to find character in String after nth index, then you can pass fromIndex to indexOf method.

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.

Output:

Index of a in String Java2blog is: 3

Find Character at Index in String in Java

Using String’s charAt() method, you can find character at index in String in java.

Let’s see with the help of example:

Output:

Character at index 5 in String Java2blog is: b

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.

Output:

Index of a in String Java2blog is: 5

That’s all about how to find character in String in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *