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:
- Increment
i
bytext1.length() - 1
each timetext1
is found andj == text1.length()
. After you incrementi
bytext1.length() - 1
, the loop’s increment part will incrementi
by1
which will result intoi
being incremented bytext1.length()
. - Modify the condition from
i < text2.length() - text1.length()
toi < text2.length()
. - Modify the condition from
j<text1.length() && found
toj < 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