In: Computer Science
VI. Answer part A, B, and C of question 5.
5a)
Given a String str1 and a String str2, return true if str1 contains any character in str2
anyChar("abc", "xyz") → false
anyChar("abc", "xya") → true
anyChar("abc", "xyzxyzbxyzxyz") → true
5b)
Given a String str1 and a String str2, return true if str1 does not contains any character in str2, and false otherwise.
noChar("abc", "xyz") → true
noChar("abc", "xya") → false
noChar("xyzxyzbxyzxyz", "xyzb") → false
5c)
Given a String str1 and a String str2, return true if str1 contains every character in str2. The empty string is contained in any other String, including the empty string itself.
everyChar("abc", "xyz") → false
everyChar("abc", "xya") → false
everyChar("xyzxyzbxyzxyz", "xyzb") → true
// 5a) public static boolean anyChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (s1.contains("" + s2.charAt(i))) { return true; } } return false; } // 5b) public static boolean noChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (s1.contains("" + s2.charAt(i))) { return false; } } return true; } // 5c) public static boolean everyChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (!s1.contains("" + s2.charAt(i))) { return false; } } return true; }
public class StringMethods { // 5a) public static boolean anyChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (s1.contains("" + s2.charAt(i))) { return true; } } return false; } // 5b) public static boolean noChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (s1.contains("" + s2.charAt(i))) { return false; } } return true; } // 5c) public static boolean everyChar(String s1, String s2) { for (int i = 0; i < s2.length(); i++) { if (!s1.contains("" + s2.charAt(i))) { return false; } } return true; } public static void main(String[] args) { System.out.println(anyChar("abc", "xyz")); System.out.println(anyChar("abc", "xya")); System.out.println(anyChar("abc", "xyzxyzbxyzxyz")); System.out.println(noChar("abc", "xyz")); System.out.println(noChar("abc", "xya")); System.out.println(noChar("xyzxyzbxyzxyz", "xyzb")); System.out.println(everyChar("abc", "xyz")); System.out.println(everyChar("abc", "xya")); System.out.println(everyChar("xyzxyzbxyzxyz", "xyzb")); } }