Mohammad Al Baba Mohammad Al Baba - 1 month ago 4
Java Question

calculating the number of string occurances in another string

this is my assi. i cant solve it using if statments since we didnt take them yet... its proving to be impossible please help:

Write a program NumStrings.java that receives two strings through the command line as

input and then prints out the number of times the second string occurs as a substring in the
first.

My bad code:

public class test {

public static void main(String[] args) {
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for(int i=0; i <= a.length()-5; i++){


for (int z=4; z<=(a.length()-1) && a.compareTo(b)==0; z++){
times = times +1;
}

}
System.out.print(times);
}


}

Answer

Here is the correct way to do it, using subString() (documentation here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)):

String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
    String substring = a.subString(i, i + b.length());
    if (substring.equals(b)) {
        times = times + 1;
    }
}
System.out.println(times);

And here is a way to do it without if statements... Which I don't recommend. But if you have to do it that way, this will work.

String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
    String substring = a.substring(i, i + b.length());
    for (int j = 0; substring.equals(b) && j < 1; j++) {
        times = times + 1;
    }
}
System.out.println(times);