Java小作业:统计一个字符串中出现某字母的次数

Java小作业:统计一个字符串中出现某字母的次数

(预习工作)涉及到的string类的方法:

  • substring(int beginIndex, int endIndex)
    返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
    注意:返回的字符串包含beginIndex,但不包含endIndex

  • indexof(int ch, int fromIndex)
    返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
    注意:索引值的范围是从0开始的,substring的索引也是从0开始

  • equals(Object anObject)
    将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。

程序设计如下:

package mypage;
/*
  从键盘输入一个字符串和指定一个字母
  统计该字符串中出现指定字母字符的次数
*/
import java.util.*;
import java.lang.String;

public mypage test01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		System.out.println("please enter a string..");//输入一个字符串
		String str = scan.nextLine();//从键盘接收
		System.out.println("please enter a letter that you want to count.. ");//请输入一个你想要统计的字母
		String world = scan.nextLine();
		System.out.println("All indexs as follows:");//返回的字母索引如下
		int count = 0;//索引计数器
		for (int i = 0; i < str.length(); i++) {
			if (world.equals(str.substring(i, i + 1))) {//判断两个字符串是否相等
				System.out.print(str.indexOf(world, i) + " ");//若相等则不换行输出索引值
				count++; 
			}
			if (i == str.length() - 1) {//当循环到最后一个字符串(只含一个字符)时
				System.out.println(); // 换行
				System.out.println("the number of occurrences:" + count+"times.");//输出索引出现的次数
			}

			scan.close();//关闭
		}

	}
}

输出如下:

please enter a string…
hahh ahhahh
please enter a letter that you want to count…
h
All indexs as follows:
0 2 3 6 7 9 10
the number of occurrences:7 times.

总结:
1)多看APK文档,真有用。
2)String类类似于数组,不需要生成对象就可以调用方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只爱圣女果

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值