本人菜鸟
判断一个字符在字符串中出现的次数,
连续出现算一次
如fdgfdfffffffffdff 出现的次数:4
// 接收字符串
System.out.println("请输入一个字符串:");
Scanner input = new Scanner(System.in);
String str1 = input.next();
// 将字符串转为字符数组
char[] ch = str1.toCharArray();
// 接收需查找的字符
System.out.println("请输入一个查找的字符:");
Scanner inputstr = new Scanner(System.in);
char input2 = inputstr.next().charAt(0);
int num = 0;
for (int i = 0; i < ch.length +1 ; i++) {
if (input2 == ch[i] || input2 != ch[i-1]) {
num++;
}
}
System.out.println("num:" + num);
在字符数组中遍历的时候,,for循环中的i < ch.length 时,如果是需要查找的字符在字符串中最后一位,那就会越界
如果是 i < ch.length - 1 就不会越界,但是,最后一个就不会遍历到