Following program shows how to search the word inside a string using indexOf(String str) available in Java. The indexOf(String str) method returns the position of word with in the string if found, otherwise it returns –1.
Sample Program
package com.javatutorialcorner.javastring;
public class WordSearch {
public static void main(String[] args) {
String jtc = "Spring tutorials @ Java Tutorials Corner";
String subString = "Java";
int index = jtc.indexOf(subString);
if (index == -1) {
System.out.println(subString + " not found");
} else {
System.out
.println("Word " + subString + " found at index " + index);
}
}
}
Output
The above code will produce the following result.
Word Java found at index 19
0 comments:
Post a Comment