Good Afternoon, I want to write a method that reaches(asks) two strings and checks whether String2 is in String1 case. If s2 is in s1 it returns the index of the last occurrence of String2, otherwise it returns -1. It's easy by using lastIndexOf() method but I do not want that. Actually, It would be much better If we do not use handy string methods(except charAt and length).
So, here is my code up to now(It is a really bad code):
int contains() {
Scanner scan0 = new Scanner(System.in);
System.out.println("Enter firts string: ");
String s1 = scan0.nextLine();
System.out.println("Enter second string: ");
String s2 = scan0.nextLine();
for(int i = 0; i<s1.length(); i++) {
for(int t = 0; t<s2.length(); t++) {
char desiredChar = s2.charAt(t);
char letter = s1.charAt(i);
if(desiredChar == letter)
System.out.print(s2.charAt(i));
}
}
return 0;
}
It gives java.lang.StringIndexOutOfBoundsException
error.