在一個長字符串b裏找子字符串,看是否等於短字符串ajava
package findChar; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class findSonString { public static String findTheSame(String a, String b) { int i,j,k; int temp=0; for(j=0;j<b.length()&&temp!=a.length();j++){ if(b.charAt(j)==a.charAt(0)){ temp=0; k=j; for(i=0;i<b.length()-j&&i<a.length();i++,k++){ if(a.charAt(i)==b.charAt(k))temp++; } } } if(temp==a.length())return "Match OK"; else return "No match"; } public static void main(String args[]) { System.out.print("請輸入字符串a:"); Scanner inputA=new Scanner(System.in); String a=inputA.next(); System.out.print("請輸入字符串b:"); Scanner inputB=new Scanner(System.in); String b=inputB.next(); String key = findSonString.findTheSame(a,b); System.out.println("匹配結果:"+key); int count=0; Matcher m=Pattern.compile(a).matcher(b); while(m.find()){ count++; } System.out.println("有多少個子字符:"+count); } }