14年的末班车,祝福准备好的人都赶上吧!
- package exercises;
- /**
- * 在字符串中查找字符出现的次数
- * @author always
- *
- */
- public class Test {
- public static void main(String[] args) {
-
- //定义字符串及要查找的字符
- String str = "abcdefabcdefabcdeffrf";
- char ch = 'f';
-
- //定义次数count
- int count;
-
- //两种方法查找
- // count = getCount_1(str, ch);
- count = getCount_2(str, ch);
-
- //打印次数
- System.out.println(count);
- }
- /**
- * 方法一,通过遍历每一个字符位置查找
- * @param str
- * @param ch
- * @return
- */
- private static int getCount_1(String str, char ch) {
- int count = 0;
- for (int i = 0; i < str.length(); i++) {
- if (str.charAt(i) == ch)
- count++;
- }
- return count;
- }
-
- /**
- * 方法二,通过indexOf出现的次数查找
- * @param str
- * @param ch
- * @return
- */
- private static int getCount_2(String str, char ch) {
- int fromIndex = 0, count = 0;
- while ((fromIndex = str.indexOf(ch, fromIndex)) != -1) {
- fromIndex++;
- count++;
- }
- return count;
- }
- }
复制代码 |