How to count the number of occurrences of a certain character in a string in a java program

#How to count the number of occurrences of a certain character in a string in java program


Example question:
Write a program to count the number of occurrences of the letter "n" and the letter "o" in the string "want you to know one thing".


Code:

	String str="want you to know one thing";//创建一个String类的对象	str,"want you to know one thing"为str对象的内容
	char[] cha=str.toCharArray();//将字符串str转换成char类型的字符数组cha
	int a=0;//声明一个int类型的变量a,赋值0
	for (int i = 0; i < cha.length; i++) {//定义一个关于字符数组cha的for循环
		if(cha[i]=='o'||cha[i]=='n'){//判断判断此次循环是否是字符'o'或者'n'
			a++;//如果是,则变量a++
		}
	}
	System.err.println(a);//在控制台输出变量a的值
	//控制台输出结果a=8;
}
	

Guess you like

Origin blog.csdn.net/chen_CJH/article/details/81416403