統計字符串中重複出現的字符串總數

使用String類中的indexOf()方法確定一字符串在另一字符串中出現次數的應用程序。例如字符串“this”在字符串“this is my first program. this…”中出現了2次。
算法思想:
當indexOf返回不爲1時候進行循環,將統計數字加一併將第一個符合條件的字符串替換掉

class Statistics
{
public static void main(String[] args)
{
String charString="this is my first program. this…";
int sum=0;
do
{
sum++;
charString=charString.replaceFirst("this","1");
}
while(charString.indexOf("this")!=-1);

System.out.println("total is "+sum);
}
}

PS:剛看着這個題目想了半天都快睡着了,突然想着這種方法,可能笨了點,不過還沒想到更好的……
如果不用String自帶的函數,可以利用循環,從0開始每次增加要查字符串的長度,逐次比較。
發佈了12 篇原創文章 · 獲贊 0 · 訪問量 2547
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章