字串拆分-查詢字元
阿新 • • 發佈:2018-12-11
1 package demo3; 2 3 import java.util.Scanner; 4 5 //輸入一個字串,仔輸入要查詢的字元,判斷該字元仔輸入字串中出現的次數 6 public class FindStr { 7 public static void main(String[] args) { 8 Scanner input=new Scanner(System.in); 9 System.out.print("請輸入字串:"); 10 String str=input.next(); 11 System.out.print("請輸入要查詢的字元:");12 String s=input.next(); 13 //實現方式一 14 // String[] a=str.split(s); 15 // System.out.println(str+"中包含"+(a.length-1)+"個"+s); //如果查詢的是最後一個字元會出現少1的情況,存在bug 16 17 18 /* String[] temp=new String[str.length()]; 19 //特定字元出現的次數 20 int count=0; 21 for (int i = 0; i < temp.length; i++) {22 temp[i]=str.substring(i, i+1); 23 if(s.equals(temp[i])) { 24 count++; 25 } 26 }*/ 27 28 //實現方式二 29 int count=0; 30 for (int i = 0; i < str.length(); i++) { 31 char a=str.charAt(i); 32 if((a+"").equals(s)) { 33 count++; 34 } 35 } 36 System.out.println("\""+str+"\"中包含"+count+"個\""+s+"\""); 37 } 38 }