用JAVA编程统计一个字符串中指定字符的出现次数

如题所述

//str为字符串,ch为指定字符,返回出现的次数
public static int count(String str,char ch){
int count = 0;
for(int i=0;i<str.length();i++){
count = (str.charAt(i)==ch)?count+1:count;
}
return count;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2007-11-22
import java.io.*;
class text
{
static BufferedReader keyboard=new
BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args)throws IOException
{
char ch='n';//指定字符
String InputString;
int count=0;
System.out.print("请输入一段字符串:");
InputString=keyboard.readLine();
for(int i=0;i<InputString.length();i++)
if(InputString.charAt(i)==ch)
count++;
System.out.println(count);
}
}
相似回答