1. 程式人生 > >【程序49】

【程序49】

import void keyword java pub ava 次數 code []

題目:計算字符串中子串出現的次數

import java.util.*;

public class lianxi49 {

public static void main(String args[]){

    Scanner s = new Scanner(System.in);

    System.out.print("請輸入字符串:");

    String str1 = s.nextLine();

    System.out.print("請輸入子串:");

    String str2 = s.nextLine();

    int count=0; 

    if(str1.equals("")||str2.equals("")) 

    { 

       System.out.println("你沒有輸入字符串或子串,無法比較!"); 

       System.exit(0); 

    } 

    else 

    { 

        for(int i=0;i<=str1.length()-str2.length();i++) 

        { 

            if(str2.equals(str1.substring(i, str2.length()+i))) 

            //這種比法有問題,會把"aaa"看成有2個"aa"子串。 

            count++; 

        } 

    System.out.println("子串在字符串中出現: "+count+" 次"); 

    } 

}

}

```

【程序49】