package JAVA;
import java.awt.List;
import java.util.ArrayList;
/**
*
* @author 梁小魚
*
*/
public class MyTest {
public static void main(String[] args) {
//查找字符串在目標字符串是否存在
Boolean isExit = IsExit("f","abfsdfsdkjl;fas;dlfsldf;asdfsdfaszdf");
System.out.println(isExit);
}
private static Boolean IsExit(String strson, String strmother ) {
//設置是否存在標志位
Boolean Isflag = false;
// 獲得母串的長度
Integer strmotherLength = strmother.length();
// 獲得子串的長度
Integer strsonLength = strson.length();
if (strmother==null||strmotherLength<strsonLength||strson.equals("")||strson==null) {
return false;
}
System.out.println("輸入的母串為:" + strmother);
System.out.println("輸入的子串為:" + strson);
//存放結果的數組
ArrayList<Boolean> reasonArr = new ArrayList<Boolean>();
//字符出現次數
Integer appTime = 0;
//將母串轉為字符數組
char[] charArrayMother = strmother.toCharArray();
//以子串長度為單位遍歷母串數組
for (int i = 0; i < (charArrayMother.length - strsonLength +1); i++) {
//遍歷起點為0,終點為數組長度減去子串長度
//以子串長度 為最小單位 遍歷比較
//寫一個比較的字方法,傳入的參數有母串數組,當前遍歷位置,子串
Integer flag = compare(charArrayMother,strson,i);
if (flag == 1) {
reasonArr.add(true);
}else {
reasonArr.add(false);
}
}
//在此結算
for (Boolean bool : reasonArr) {
if (bool==true) {
appTime += 1;
}
}
System.out.println("字符:" + strson + " 在 " + strmother + " 中出現的次數為:" + appTime + "次!");
if (appTime>0) {
return true;
}
return Isflag;
}
/**
* 處理比較的方法
* @param charArrayMother
* @param strson
* @param i
* @return
*/
private static Integer compare(char[] charArrayMother, String strson, int i) {
// 取出當前遍歷位置,所形成的子串長度單位的字符
// 創建一個字符床存放拿出來的字符
String comstr = "";
for (int j = 0; j < strson.length(); j++) {
char c = charArrayMother[i+j];
comstr += String.valueOf(c);
}
System.out.println("第"+ (i+1) + "截取的字符串為:" + comstr);
if (strson.equals(comstr)) {
return 1;
}
return 0;
}
}