1. 程式人生 > 其它 >Java實現字串中的contains方法與indexof方法

Java實現字串中的contains方法與indexof方法

技術標籤:JAVA

contains方法思路:

  1. 設定兩個標記點分別標記被查詢的字串當前位置與目標字串當前的位置。
  2. 遍歷整個被查詢字串,若兩個標記點的字元相等則同時後移,當目標字串移到最後一位並且 通過檢驗時則返回true。
  3. 若在遍歷過程中兩個標記點的字元不相等時則將標記目標字元的標記點 置為0,標記被查詢的字串標記點繼續後移。
  4. 若遍歷完整個被查詢字元仍未找到時則返回false。

程式碼如下:

package T0119;

import java.util.Arrays;

public class TE01_19 {
    public static void main(String[] args)
{ String a="world|world|hello|zs"; String c="hello"; String b="zs"; String d="well"; System.out.println(Contain(a,b)); System.out.println(Contain(a,d)); } public static boolean Contain(String num,String target)
{ //設定兩個標記,t用來標記字串num當前的位置,i標記字串target當前的位置 int t=0; int i=0; //遍歷整個字串 while(t<num.length()){ //若當前字串中的字元與目標字串中的字元相等則檢驗下一個 if(target.charAt(i)==num.charAt(t)){ t++; i++; //當檢驗全部驗證通過時則返回true if
(i==target.length()-1) return true; } //若當前字串中的字元與目標字元不相等時則將t向後移而i則置為0 else if(target.charAt(i)!=num.charAt(t)){ t++; i=0; } } ///當檢驗完後並未找到目標字串則返回false return false; } }

執行結果如下:
在這裡插入圖片描述
indexof方法實現思路與contains實現思路幾乎一致,因此我們直接看程式碼。
程式碼如下:

package T0119;

import java.util.Arrays;

public class TE01_19 {
    public static void main(String[] args) {

        String a="world|world|hello|zs";
        String c="hello";
        String b="zs";
        String d="well";
        System.out.println(Indexof(a,b));
        System.out.println(Indexof(a,d));

    }
   
    public static int Indexof(String num,String target){
        int count=0;
        int t=0;
        int i=0;
        while(t<num.length()){
            if(target.charAt(i)==num.charAt(t)){
                t++;
                i++;
                if(i==target.length()-1){
                    count=t-i;
                    return count;
                }
            }else if(target.charAt(i)!=num.charAt(t)){
                t++;
                i=0;
            }
        }
        System.out.println("該字串中不含有目標字串因此返回0");
        return 0;
    }
    
}


執行結果如下所示:
在這裡插入圖片描述
如有不足還請指出,謝謝!