How to Get Characters by Index from a String in Java


In this example, let’s us see how to get the location of the specified character using the indexOf() method, as shown below.

Source Code

package com.beginner.examples;

public class RetrieveTheCharacterExample {

	public static void main(String[] args) {

		String string = "abcdefghijklmnopqrstuvwxyz";

		// Get the index of 'q'
		int indexQ = string.indexOf('q');

		System.out.println("The index of the character 'q' in the string is: " + indexQ);
		
		// Get the index of 'c'
		int indexC = string.indexOf('c');

		System.out.println("The index of the character 'c' in the string is: " + indexC);

	}

}

Output:

The index of the character 'q' in the string is: 16
The index of the character 'c' in the string is: 2
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments