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