第一:有两个字符串A和B,判断B在A中出现的次数
//面试题1:
//有两个字符串A和B,判断B在A中出现的次数
public static void main(String[] args) {
count("abcabcab", "a");//测试count方法
}
public static int count(String str, String sub) {
String subString;
int length = sub.length();
int count = 0;
for (int i = 0; i < str.length()-length+1; i++) {
subString = str.substring(i, i + length);//substring(),起始值和结束值
if (sub.equals(subString))
count++;
}
System.out.println(count);
return count;
}
第二:有两个字符串,判断A字符串的每一个单个字符在B字符串中出现的次数
public static void main(String[] args) {
test("afdsds", "aaaffffddddddsssssss");
}//测试
public static void test(String A, String B) {
char[] a = A.toCharArray();
char[] b = B.toCharArray();
for (int i = 0; i < a.length; i++) {
int count = 0;
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
count++;
}
}
System.out.println(a[i] + "出现的次数:" + count);
}
}