Java Tutorial
In java programming, indexOf method is used to find the index of sub string in the string.
indexOf method returns index if sub string is found in the string, otherwise returns -1.
This java program is used to check whether word or substring is found in the string or not.
Here string and word are both user inputs.
indexOf method is used to search the word in string from left to right.
import java.util.Scanner; public class SearchString { public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Search word in string"); System.out.println("-----------------------"); System.out.print("Enter String: "); String str = sc.nextLine(); System.out.print("Enter word to search: "); String word =sc.next(); int index = str.indexOf(word); if(index >= 0){ System.out.print("Search Found index: "); System.out.println(index); } else { System.out.println("No Search Found!"); } } }Output:
D:\Java_Programs>javac SearchString.java D:\Java_Programs>java SearchString Search word in string ---------------------- Enter String: This is testing in progress Enter word to search: testing Search Found index: 8 D:\Java_Programs>javac SearchString.java D:\Java_Programs>java SearchString Search word in string --------------------- Enter String: This is testing in progress Enter word to search: searching No Search Found!
lastIndexOf method returns index if sub string is found in the string and matches from end to beginning of the string, otherwise returns -1.
import java.util.Scanner; public class SearchString { public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.println("Search word in string from right to left"); System.out.println("------------------------------------------"); System.out.print("Enter String: "); String str = sc.nextLine(); System.out.print("Enter word to search: "); String word =sc.next(); int index = str.lastIndexOf(word); if(index >= 0){ System.out.print("Search Found index: "); System.out.println(index); } else { System.out.println("No Search Found!"); } } }Output:
D:\Java_Programs>javac SearchString.java D:\Java_Programs>java SearchString Search word in string from right to left ------------------------------------------ Enter String: This is testing codingpointer.com and is to identify issues! Enter word to search: is Search Found index: 53 D:\Java_Programs>javac SearchString.java D:\Java_Programs>java SearchString Search word in string from right to left ------------------------------------------ Enter String: This is testing in progress Enter word to search: searching No Search Found!
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page