编写一个程序,输出一个字符串中大写英文字母、小写英文字母、非英文字母的个数 编写一个方法,计算指定子串在字符串中出现的次数 // StringTest.java import java.util.*; public class StringTest{ public static void main(String[] args){ Scanner in=new Scanner(System.in); System.out.print("请输入测试字符串:"); String string=in.nextLine(); int upperCase=0; int lowerCase=0; int others=0; System.out.println("你输入的字符串是:" + string); for(int i=0;i<string.length();i++){ char c=string.charAt(i); if(c>='a' && c<='z') lowerCase++; else if(c>='A' && c<='Z') upperCase++; else others++; } System.out.println("字符串中所有字符总数是: "+ string.length()); System.out.println("字符串中大写英文字母数是:" + upperCase); System.out.println("字符串中小写英文字母数是:" + lowerCase); System.out.println("字符串中非英文字符数是: " + others); System.out.println("/n----------------------------/n"); System.out.println("请输入指定字符串(测试指定字符串在上述测试字符串中出现的次数) : "); String str=in.nextLine(); System.out.println("测试字符串是: " + string); System.out.println("指定字符串是: " + str); System.out.println("指定字符串在测试字符串中出现的次数(indexOf)是: " + StringTest.strTimes(string,str)); System.out.println("指定字符串在测试字符串中出现的次数(substring)是: " + StringTest.strTimes2(string,str)); } // 测试指定字符串 str 在测试字符串string 中出现的次数 public static int strTimes(String string,String str){ // 用 indexOf() 方法实现 int times=0; int index=0; while(index>=0 && index < string.length()){ index = string.indexOf(str,index) ; if(index != -1) // 没有指定子串返回 -1 times++; else break; index += str.length(); // System.out.println("index " + index + " t " + times ); } return times; } public static int strTimes2(String string,String str){ // 用substring() 方法实现 int times=0; for(int i=0;i<string.length()-str.length();i++){ String s=string.substring(i,i+str.length()); if(s.equals(str)) times++; } return times; } }