In: Computer Science
Java
Write a method that counts how many times one string appears in another string. The method takes three input parameters: two Strings and one Boolean. The Boolean value determines whether the words are allowed to overlap each other. For example:
When the method is called with input parameters (“balloon”, “oo”, false), it returns 1.
When the method is called with input parameters (“hh”, “hhhhhh”, true) returns 5.
When the method is called with input parameters (“cc”, “abcdefg”, true), returns 0.
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== public static int overlaps(String s, String check, boolean overlappingAllowed) { int count = 0; if (s.length() < check.length()) { String temp = s; s = check; check = temp; } if (overlappingAllowed) { for (int i = 0; i <= s.length() - check.length(); i++) { if (s.substring(i, i + check.length()).equals(check)) { count += 1; } } } else { for (int i = 0; i <= s.length() - check.length(); i++) { if (s.substring(i, i + check.length()).equals(check)) { count += 1; i = i + check.length() - 1; } } } return count; }
===================================================================
// PROGRAM TO TEST WITH THE GIVEN EXAMPELS
public class Overlap { public static int overlaps(String s, String check, boolean overlappingAllowed) { int count = 0; if (s.length() < check.length()) { String temp = s; s = check; check = temp; } if (overlappingAllowed) { for (int i = 0; i <= s.length() - check.length(); i++) { if (s.substring(i, i + check.length()).equals(check)) { count += 1; } } } else { for (int i = 0; i <= s.length() - check.length(); i++) { if (s.substring(i, i + check.length()).equals(check)) { count += 1; i = i + check.length() - 1; } } } return count; } public static void main(String[] args) { System.out.println(overlaps("balloon","oo",false)); System.out.println(overlaps("hh","hhhhhh",true)); System.out.println(overlaps("cc","abcdefg",true)); } }