java

How to search a character in a string in Java

In this tutorial, we are going to see how to search for a word or a character in a string in Java. In the following example, we’ll use the indexOf() method which returns the position of the first occurrence of the characters specified in a string. You can use the lastIndexOf() method to return the position of the last occurrence of the specified characters in a string.
 

How to search a character in a string in Java
public class Main {
	public static void main(String[] args) {
		
		String str = "Welcome to StackHowTo";
		
		int index = str.indexOf("StackHowTo");
		
		if(index == - 1) {
			System.out.println("The word StackHowTo does not exist.");
		} else {
			System.out.println("The word StackHowTo found at the index : " + index);
		}
	}
}

Output:

The word StackHowTo found at the index : 11
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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