I'm trying to solve this problem but it doesn't seem to work in any way. I tried to search for the problem but all other answers use methods or arrays and we haven't studied them yet so I have to solve the problem with loops only. This is the question:
Write a program that returns number of occurrences of a string in another string.
E.g.
Input:
First String: the
Second String: the students are working hard in the faculty of Engineering because they love it
Output:
3
this is what I tried:
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
int count = 0;
String text="";
for(int i = 0; i<s1.length(); i++){
for(int j =0; j<=s2.length() ; j++){
if(s1.charAt(i)==s2.charAt(j) && i ==0){
for(int m=1; m<s1.length();m++){
if(s1.charAt(i+1)==s2.charAt(j+1)){
if(m==s1.length()){
count++;
}else{
break;
}
}
}
}
}
}
System.out.println(count);
I think I have a problem with the logic. This is what I'm thinking: the program should check the first letter of the first string then check if it checks if it equals the first letter of the second string, then if it doesn't equal it then the program should loop through the second string until it finds a letter that equals the first letter of the first string, if it finds a letter that equals the first string it checks if the second letter of the first string equals the next letter of the other string, if yes then it checks if thats the last letter of the first string if it is then count increases by one, if it isn't it loops the the next characters. I tried to do it a couple of other ways non of my code worked. Can someone help me with the logic?