We can search for a word in any String object using indexOf() method which returns the position of the word within the string. If the word or letter is not found then it returns -1.
Class name: FindTheWord.java
import java.util.*;
public class FindTheWord {
public static void main(String[] args) {
String strOrig = "Hello world";
int intIndex = strOrig.indexOf("world");
if(intIndex == - 1){
System.out.println("world not found");
}else{
System.out.println("Found world at index " + intIndex);
}
}
}
OUTPUT:
Found world at index 6
No comments:
Post a Comment