In: Computer Science
IV. Answer parts A,B, and C
4a)
Return true if the letter 'a' occurs in the given String, and false otherwise.
containsA("abc") → true
containsA("wxyz") → false
containsA("bcaca") → true
4b)
Return true if the letter 'a' does not occur in the given String, and false otherwise.
notContainsA("abc") → false
notContainsA("wxyz") → true
notContainsA("bcaca") → false
4c)
Count the number of times a given char occurs in a given range of a String parameter (i.e. starting at a given start index, and up to but not including and end index). If end is greater than the length of the String, then the method should stop looking at the end of the String.
countCharsInRange("java", "v", 1, 2) → 0
countCharsInRange("java", "v", 0, 2) → 0
countCharsInRange("java", "v", 0, 3) → 1
// 4a) public static boolean containsA(String s) { return s.contains("a"); } // 4b) public static boolean notContainsA(String s) { return !s.contains("a"); } // 4c) public static int countCharsInRange(String s, String ch, int start, int end) { int count = 0; for (int i = start; i < end; i++) { if (s.charAt(i) == ch.charAt(0)) ++count; } return count; }
public class StringMethods { // 4a) public static boolean containsA(String s) { return s.contains("a"); } // 4b) public static boolean notContainsA(String s) { return !s.contains("a"); } // 4c) public static int countCharsInRange(String s, String ch, int start, int end) { int count = 0; for (int i = start; i < end; i++) { if (s.charAt(i) == ch.charAt(0)) ++count; } return count; } public static void main(String[] args) { System.out.println(containsA("abc")); System.out.println(containsA("wxyz")); System.out.println(containsA("bcaca")); System.out.println(notContainsA("abc")); System.out.println(notContainsA("wxyz")); System.out.println(notContainsA("bcaca")); System.out.println(countCharsInRange("java", "v", 1, 2)); System.out.println(countCharsInRange("java", "v", 0, 2)); System.out.println(countCharsInRange("java", "v", 0, 3)); } }