栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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类类似于数组,不需要生成对象就可以调用方法。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/786488.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号