已知一個字符串S 以及長度為n的字符數組a,編寫一個函數,統計a中每個字符在字符串中的出現次數
阿新 • • 發佈:2019-03-07
lin sta imp scanner col div created rip void
import java.util.Scanner; /** * @author:(LiberHome) * @date:Created in 2019/3/6 21:04 * @description: * @version:$ */ /*已知一個字符串S 以及長度為n的字符數組a,編寫一個函數,統計a中每個字符在字符串中的出現次數 * 要求函數用s,a,n為參數,返回值為一維整形數組*/ public class CountTimes { public static void main(String[] args) { System.out.println("請輸入一段字符串"); Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); char[] a = {‘a‘,‘b‘,‘c‘,‘a‘,}; int n = a.length; int[] result = new int[n]; result=countTiming(s,a,n); show(result); } private static void show(int[] arrs) { for (int i = 0; i < arrs.length; i++) { System.out.print(" "+arrs[i]+"times"); } } private static int[] countTiming(String ss, char[] aa, int nn) { /*計算數組a中每個元素的出現次數*/ int[] answer = new int[nn]; char[] ssArr = ss.toCharArray();int count=0; /*將aa數組裏面的每一個元素作為對比目標,掃描一遍ssArr數組,將掃描到的次數存放在一個數組中最後返回*/ for (int i = 0; i < aa.length; i++) { for (int j = 0; j < ssArr.length; j++) { if (ssArr[j]==aa[i]){ count++; } } answer[i]=count; count=0; } return answer; } }
已知一個字符串S 以及長度為n的字符數組a,編寫一個函數,統計a中每個字符在字符串中的出現次數