Hey guys,
Here is the question: Design Java code to find and return the frequency of string b in string a.
For example , if string a = "abcdabcfabxyabd" and string b = "ab"
The frequency should be equal to 4
Here is my code:
import java.util.*; public class StringFrequency_A_in_B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1, s2; String commonChars = ""; int lengthCommon = 0; System.out.println("The program will find the characters " + "quantity/frequancy \nof the first string in the second string"); System.out.println("Now, enter two strings in seperate lines"); s1 = scan.nextLine(); s2 = scan.nextLine(); int len = s1.length(); // number of characters in string A for (int i = 1; i < len ; i++) { char ch = s1.charAt(i); if (s2.indexOf(ch) != -1) { commonChars = commonChars + ch; } } // end of the loop lengthCommon = commonChars.length(); System.out.println("The common characters: " + commonChars); System.out.println("The frequency of common characters: ” + lengthCommon); System.exit(0); } }
The thing is that it doesn't count the frequency of "ab", but the quantity of a's and b's, so it shows 8. How do I make it count frequency of "ab" string?