編寫一個方法,輸出在一個字符串中,指定字符串出現的次數。


 1 public class Test {
 2     public static void main(String args[]) {
 3         String s = "I love java and I want to learn java!";
 4         String findString = "java";
 5         int count = Test.countString(s,findString);
 6         System.out.print("字符串個數為: " + count);
 7     }
 8     
 9     public static int countString(String s1, String s2) {
10         int count = 0; 
11         int findIndex = 0;
12         int findLen = s2.length();
13         findIndex = s1.indexOf(s2);
14         while(findIndex != -1){
15             s1 = s1.substring(findIndex + findLen);
16             findIndex = s1.indexOf(s2);
17             count++;
18         }
19         return count;
20     }
21     
22 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM