Java Tutorial
Reads the string using Scanner class and nextLine method from java.util package and finds whether user input search string is part of sentence string in java program.
Java string method indexOf is used here to check whether string contains or not since indexOf method returns the string matching starting position index value in the main string 'sentence' variable.
If does not contains the string, returns -1.
import java.util.Scanner; class StringContainsTest{ public static void main(String[] args){ String sentence = "Welcome to learn java!"; System.out.print("Enter string to search: "); Scanner sc=new Scanner(System.in); String findStr = sc.nextLine(); sc.close(); if (sentence.indexOf(findStr) >= 0){ System.out.println("Sentence '"+sentence+"' contains the substring '"+findStr+"'"); } else { System.out.println("Sentence '"+sentence+"' does not contain the substring '"+findStr+"'"); } } }Output:
D:\Java_Programs>javac StringContainsTest.java D:\Java_Programs>java StringContainsTest Enter string to search: learn Sentence 'Welcome to learn java!' contains the substring 'learn' D:\Java_Programs>javac StringContainsTest.java D:\Java_Programs>java StringContainsTest Enter string to search: not Sentence 'Welcome to learn java!' does not contain the substring 'not'
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page