public static void main(String[] args) {
String str = “ABC123ABC”;
char searchChar = ‘B’;
int count = 0;
char[] charArray = str.toCharArray();
for (char item : charArray) {
if (item == searchChar) {
count++;
}
}
System.out.println("字符" + searchChar + "出现的次数为:" + count);
}
输出结果如下所示:
字符B出现的次数为:2
但面试题肯定不会这么简单,紧接着面试官增加了限制条件:
> 如果不能使用循环,只使用String自己的方法,如何实现呢?
实现方法有很多种,但我推荐使用replace()方法,很好理解,并且高效,代码如下所示:
public static void main(String[] args) {
String str = “ABC123ABC”;
String searchChar = “B”;
int count = 0;
int origialLength = str.length();
str = str.replace(searchChar, "");
int newLength = str.length();
count = origialLength - newLength;
System.out