题目一:
编写一个应用程序,统计输入的一个字符串中相同字符的个数,并将统计结果输出。
代码:
1.Test.java
1 package cn.edu.ccut; 2 import java.util.*; 3 4 public class Test { 5 6 public static void main(String[] args) { 7 System.out.println("请输入字符串"); 8 Scanner sc = new Scanner(System.in); 9 String str1 = sc.nextLine(); // 从键盘接受字符串输入; 10 for(int i = 0 ; i < str1.length() ; i++){ 11 char c = str1.charAt(i); // 拆分单个字符; 12 String str2= new Character(c).toString(); // char类型装换成String; 13 if(str1.indexOf(c) == i){ //判断该字符是否第一次出现; 14 int count = 0; 15 for(int j = 0 ; j < str1.length() ; j++){ 16 if(str1.regionMatches(j, str2, 0, 1)){ //查找相同字母; 17 count++; 18 } 19 } 20 System.out.println(""+c+"出现了"+count+"次"); 21 } 22 } 23 } 24 }
运行结果:
原文:https://www.cnblogs.com/chris-wang/p/11892422.html