public class Demo {
public static void main(String[] args) {
String strone = "run Hello World code. This is my java code";
String strtwo = "code";
int count = strone.split(strtwo).length; // 用字符串2去拆分字符串1,拆分后得到的数组长度-1就是字符串2在字符串1中出现的次数
System.out.println("strtwo在strone中出现了" + count + "次");
System.out.print("strtwo 中的每个字符: ");
for (char cInStr2 : strtwo.toCharArray()) {
// 遍历strtwo中的每一个字符, 声明变量记录当前字符在strone中出现的次数
int charCount = 0;
for (char cInStr1 : strone.toCharArray()) {
// 比较当前字符和strone中的每个字符,如果相同,当前字符出现的次数就+1
charCount += cInStr1 == cInStr2 ? 1 : 0;
}
System.out.print("\"" + cInStr2 + "\"在strone中出现了" + charCount + "次,");
}
}
}
温馨提示:答案为网友推荐,仅供参考