字符串应用_统计字符串中某个字符的个数

/* 统计字符串中,某个字符的个数 */
import java.util.Scanner;

class Count{
String str2;//该成员变量用于方法二,以测试不带形参的方法
String ch2;

//方法一
public void method1(String str, String ch) {
String[] strs = str.split(""); //从数组第二个元素(数组[1])开始返回每个字符
int count = 0;
for (int i=1; i<strs.length; i++) {
if (strs[i].equals(ch)) { //这里之前犯的错误:将equals(ch)写成equals("ch:),多了引号
count++;
}
}
System.out.print("\n方法一统计该字符的个数为:"+count);
}
//方法二
public void method2(){
int count = 0;
int len = str2.length();//将字符串长度赋给len,以确定新建字符数组的长度
String[] strs = new String[len];
for (int i=0; i<len; i++) {
strs[i] = str2.substring(i, i+1); //每次从字符串中提一个字符
if (strs[i].equals(ch2)) {
count++;
}
}
System.out.println("\n方法二统计该字符的个数为:"+count);
}
}

public class Dm{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("请输入任意字符串:");
String str = input.nextLine(); // nextLine此扫描器执行当前行,并返回跳过的输入信息(即读入整行,包括空格)
System.out.print("请输入要查找的字符:");
String ch = input.nextLine();

//实例化对象
Count test = new Count();
test.method1(str, ch);
test.str2 = str;
test.ch2 = ch;
test.method2();
}
}
/*---------------------------------
请输入任意字符串:盘盘放着碗碗,碗碗盛着饭饭。
请输入要查找的字符:碗

方法一统计该字符的个数为:4
方法二统计该字符的个数为:4

---------------------------------*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值