public class PatternMathch { /** * 先求出pattern 的長度按此長度截取子字符串,而後與pattern進行比較 * @param target * @param pattern * @return */ public static int matches1(String target, String pattern){ int resultLength = pattern.length(); int resultPosition=-1; for (int i = 0; i < target.length()-resultLength; i++) { String currentResult = target.substring(i, i+resultLength); if (pattern.equals(currentResult)) { resultPosition = i; } } return resultPosition; } /** * 樸素的模式匹配,從找到的第一個字符開始, * 若遇到與Pattern不一樣的則結束這次比較從下一個字符串開始重複上面的比較直到出現匹配 * @param target * @param pattern * @return */ public static int matches2(String target, String pattern){ char[] targetArray = target.toCharArray(); char[] patternArray = pattern.toCharArray(); int result = -1; for (int j = 0; j < targetArray.length; j++) { int position = j; for (int i = 0; i < patternArray.length; i++) { if (targetArray[position]==patternArray[i]) { position++; }else { break; } } if ((position-j)==patternArray.length) { result = j; return result; } } return result; } /** * KMP模式匹配問題 未完成 * @param target * @param pattern * @return */ public static int matches3(String target, String pattern){ int result = -1; return result; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String aString ="szadftyusfsrg"; String bString ="tyu"; System.out.println(matches2(aString, bString)); } }