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

2025-01-01 19:55:27
推荐回答(2个)
回答1:

//str为字符串,ch为指定字符,返回出现的次数
public static int count(String str,char ch){
int count = 0;
for(int i=0;i count = (str.charAt(i)==ch)?count+1:count;
}
return count;
}

回答2:

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 if(InputString.charAt(i)==ch)
count++;
System.out.println(count);
}
}