Skip to content
Advertisement

occurrences of a string in another string using nested loops

the exercise asking for using only loops not construction functions or arrays every help on all sites using arrays and construction functions. I took a week to reach the code, and study alot of trials and looking for similar problem set but all help , not reach to last step input: string 1: ooo string 2: Wooooooooow

output: 7 that not correct

output must be (3) my code working in all strings input but incorrect at duplicated letters

    Scanner input = new Scanner(System.in);
    String text1 = input.nextLine();
    String text2 = input.nextLine();
    int res = 0;
    for (int i=0;i<text2.length()-text1.length();i++)
    {
       if (text1.charAt(0) == text2.charAt(i))
       {
          boolean found = true;
          for (int j=0;j<text1.length() && found;j++)
              if (text1.charAt(j) != text2.charAt(i+j))
                  found = false;
          if (found)
              res++;
       }
    }
    System.out.println(res);

Advertisement

Answer

You are almost there. With the following changes, your code will work as expected:

  1. Increment i by text1.length() - 1 each time text1 is found and j == text1.length(). After you increment i by text1.length() - 1, the loop’s increment part will increment i by 1 which will result into i being incremented by text1.length().
  2. Modify the condition from i < text2.length() - text1.length() to i < text2.length().
  3. Modify the condition from j<text1.length() && found to j < text1.length() && found && i + j < text2.length().

You can also make your program more efficient by breaking the inner loop as soon as the condition, text1.charAt(j) != text2.charAt(i + j) becomes true.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the substring: ");
        String text1 = input.nextLine();
        System.out.print("Enter the string to search into: ");
        String text2 = input.nextLine();
        int res = 0;
        for (int i = 0; i < text2.length(); i++) {
            if (text1.charAt(0) == text2.charAt(i)) {
                boolean found = true;
                int j;
                for (j = 0; j < text1.length() && found && i + j < text2.length(); j++) {
                    if (text1.charAt(j) != text2.charAt(i + j)) {
                        found = false;
                        break;
                    }
                }
                if (j == text1.length() && found) {
                    res++;
                    i += text1.length() - 1;
                }
            }
        }
        System.out.println(res);
    }
}

A sample run:

Enter the substring: ooo
Enter the string to search into: Wooooooooow
3

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement