在没有IndexOf方法的现有字符串中查找子字符串的索引

时间:2018-02-12 23:12:57

标签: java

目前正在尝试查找有关如何在现有字符串中查找子字符串索引的一些信息。例如,如果我的字符串是" HelloWorld"我的子串传递给我的方法是" world"返回索引是5.我不想使用indexOf方法只是因为我想实际了解indexOf方法实际上是如何从头开始工作的。

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

      String n1 = new String("Helloworld, welcome");
      System.out.println(n1.findIndexOf("wo"));
      System.out.println(n1.findIndexOf("we"));
      System.out.println(n1.findIndexOf("llo"));

}

public class MiniStr
{
   private String str;


   public MiniStr(String x)
   {
      this.str = x;
   }

     public int findIndexOf(String x)
       {



       }
}

2 个答案:

答案 0 :(得分:1)

我相信你想做这样的事情...... 编辑:这应该检查你的对象字符串中是否有一个等于参数的子字符串,如果是,则返回起始索引,否则返回-1

   public class TestMiniString {
        public static void main(String[] args) {
           MiniStr n1 = new MiniStr("Helloworld");
           System.out.println(n1.findIndexOf("wo"));

    }

    public class MiniStr {
      private String str;

      public MiniStr(String x){
        this.str = x;
      }

      public getStr() {
         return this.str;
      }

       public int findIndexOf(String sub) {

          for (int i=0; i<getStr().length(); i++) {
              if (getStr().charAt(i) == sub.charAt(0)) {
                  int sumEq = 1;
                  for (int j=1; j<sub.length(); j++) {
                     if (sub.charAt(j) != getStr().charAt(i+j)) break;
                     else sumEq++;
                  }
                  if (sumEq == sub.length()) return i;
              }
          }
          return -1; //in case it is not an actual substring
       }
    }

答案 1 :(得分:-1)

您可以在此处了解indexOf方法的实际工作原理 ECMAScript 5.1 (ECMA-262)

相关问题