-2

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.

Firat
  • 381
  • 1
  • 5
  • 17

1 Answers1

1

you don't check for the occurrence of the characters of s2 in s1. you will need to go through s1 char by char and check if that char and the following once are matching s2. mean if you have the strings as given you iterate through s1 and take for example the first char=M and the next 2 so you have 3 chars just like in s2. then you have Mis and the since they don't match you have to go to the next char and the followings which would then be iss and so on until you have matching strings. once you have them you can return the index of the first char of the string in s1.

Aelop
  • 156
  • 9