字符串拆分-查找字符

 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 }

猜你喜欢

转载自www.cnblogs.com/baichang/p/10105556.html