Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Find if a String2 is substring of String1
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; /* Find if a String2 is substring of String1. If it is, return the index of the first occurrence. else return -1. Eg 1:Input: String 1: test123string String 2: 123 Output: 4 Eg 2: Input: String 1: testing12 String 2: 1234 Output: -1 */ class Rextester { public static void main(String args[]) { int index=-1; Scanner input=new Scanner(System.in); System.out.println("Enter the main string:"); String mainString=input.next(); char mainStringArray[]=mainString.toCharArray(); System.out.println("Enter the substring:"); String subString=input.next(); for(int i=0;i<mainStringArray.length;i++) { if(mainStringArray[i]==subString.charAt(0)) { System.out.println("i :"+i); String temp=""; int tempit=i; if((tempit+(subString.length()-1))<mainStringArray.length) { for(int j=tempit;j<(tempit+subString.length());j++ ) { temp=temp+mainStringArray[j]; } } if(temp.equals(subString)) { index=i; break; } } } System.out.println("Starting index: "+index); } }
run
|
edit
|
history
|
help
0
Reverse Prime
PE #9
темп
ArrayOperation
Java Switch
Trapping Rain Water
AVL-GO-FLAT
4.A
Day 1
Engine Java