2016-11-22 27 views
1

注意:此問題需要提供學校作業。我墮落了,我越來越接近真實的代碼,只剩下幾點要照顧。在不使用lastIndexOf方法的情況下打印字符串中的最後一個索引

我要求寫接收兩個字符串(S1和S2),並檢查 S2是否是在S1中情況下敏感的方法。如果s2在s1中,它返回s2最後一次出現的索引,否則返回-1。

所以,這裏是我的代碼:

import java.util.*; 
public class homework4 { 


    public static void main(String args[]) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("\nEnter a choice: "); 
     int choice = input.nextInt(); 
     if(choice == 1) { 
      System.out.println("Enter firts string: "); 
       String s1 = input.next(); 
      System.out.println("Enter second string: "); 
       String s2 = input.next(); 
      System.out.print(contains(s1,s2)); 
      } 
      else { 
       //Call other methods... 
      } 
    public static int contains (String s1, String s2) { 
     for(int i = 0; i<s1.length(); i++) { 
      for(int j = 0; j<s2.length(); j++) { 
       char ch = s2.charAt(j); 
       if(s1.charAt(i) == ch) { 
        return i; 
       } 
      } 
     } 
     return -1; 
    } 

但是這個方法返回的S2第一個索引,或者它僅僅是一個的IndexOf方法的副本。 s1 = aabbccbbes2 = bb的輸出是2

編輯:@利的代碼

import java.util.*; 
    public class homework4 { 


     public static void main(String args[]) { 
      Scanner input = new Scanner(System.in); 
      System.out.println("\nEnter a choice: "); 
      int choice = input.nextInt(); 
      if(choice == 1) { 
       System.out.println("Enter firts string: "); 
        String s1 = input.next(); 
       System.out.println("Enter second string: "); 
        String s2 = input.next(); 
       System.out.print(contains(s1,s2)); 
       } 
       else { 
        //Call other methods... 
       } 
     public static int contains(String s1, String s2) { 
     int i = s2.length()-1, j = s1.length()-1; 

     if(i > j) 
      return -1; 

     for(; i > -1; i--) { 
      for(; j >= 0; j--) { 
       if(s1.charAt(j) == s2.charAt(i)) { 
        if(i == 0) 
         return j; 

        if(j != 0) 
         j--; 

        break; 
       } else if(i != s2.length()) { 
        i = s2.length()-1; 
       } 
      } 
     } 

     return -1; 
    } 
+0

'包含(「問候」,「錯誤」)'返回'2'我認爲,即使'「問候」'不含'「錯誤」',它應該因此返回'-1'。 – Gendarme

+0

@Gendarme'contains(「Greetings」,「error」)'returned'1'。 – f1r4tc

+0

是的,你說得對。更奇怪。它返回它們都有的第一個字母's1'中的索引,在這種情況下是'r'。 – Gendarme

回答

1

首先,關閉你打開當你用它做任何資源。

input.close(); 

如果允許你可以使用正則表達式:

public static int contains (String s1, String s2) { 
    Pattern p = Pattern.compile(s2+"(?!.*"+s2+")"); 
    Matcher m = p.matcher(s1); 

    if(m.find()) 
     return m.start(); 

    return -1; 
} 

的正則表達式解釋here

使用find()確保至少存在一個匹配項。 由於該模式可以產生1個且僅有1個結果,因此您可以在匹配器中請求「首次出現的第一個索引」,使用start()來實現。

編輯 好吧,我可以看到你不能使用任何東西,但charAtlength。 這裏有沒有正則表達式,子,的indexOf或什麼那麼以往不同的解決方案:

public static int contains(String s1, String s2) { 
    int i = s2.length()-1, j = s1.length()-1; 

    if(i > j) 
     return -1; 

    for(; i > -1; i--) { 
     for(; j >= 0; j--) { 
      if(s1.charAt(j) == s2.charAt(i)) { 
       if(i == 0) 
        return j; 

       if(j != 0) 
        j--; 

       break; 
      } else if(i != s2.length()) { 
       i = s2.length()-1; 
      } 
     } 
    } 

    return -1; 
} 

我必須承認,我並沒有徹底測試此。

FINAL 我已經爲你做了一些小的修復。我不知道你是如何編輯你在帖子中編輯的內容的。這裏的工作示例:

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class homework4 { 
    public static void main(String args[]) { 
     Scanner input = new Scanner(System.in); 

     System.out.println("Enter choice: "); 

     switch (input.nextInt()) { 
     // If 1 is given as input... 
     case 1: 
      // As we press "enter" after inputting 1, the newline is read by the 
      // scanner. We skip this newline by doing this. 
      input.nextLine(); 

      System.out.println("Enter first string: "); 
      String s1 = input.nextLine(); 

      System.out.println("Enter second string: "); 
      String s2 = input.nextLine(); 

      System.out.println("Result: " + contains(s1, s2)); 
      break; 
     // If 2 is given as input (just for the sake of the example) 
     case 2: 
      System.out.println("You chose an unimplemented choice."); 
      break; 
     // If something else is given as input... 
     default: 
      System.out.println("Nothing to do..."); 
      break; 
     } 

     // As Scanner is considered a resource, we have to close it, now that 
     // we're done using it. 
     input.close(); 
    } 

    // This is the RegEx implementation 
    public static int containsRegx(String s1, String s2) { 
     Pattern p = Pattern.compile(s2 + "(?!.*" + s2 + ")"); 
     Matcher m = p.matcher(s1); 

     if (m.find()) 
      return m.start(); 

     return -1; 
    } 

    // This is the charAt and length only 
    public static int contains(String s1, String s2) { 
     int i = s2.length() - 1, j = s1.length() - 1; 

     if(i > j || i * j == 0) 
      return -1; 

     for (; i > -1; i--) { 
      for (; j >= 0; j--) { 
       if (s1.charAt(j) == s2.charAt(i)) { 
        if (i == 0) 
         return j; 

        if (j != 0) 
         j--; 

        break; 
       } else if (i != s2.length()) { 
        i = s2.length() - 1; 
       } 
      } 
     } 

     return -1; 
    } 
} 
+0

非常感謝,但這不是我要找的。這個方法返回任何s1中帶有空格的「-1」。 – f1r4tc

+0

你正在做一件非常奇怪的事情。 – eli

+0

測試: String s1 =「快速的棕色狐狸跳過懶狗。」; String s2 =「the」; 退貨(按預期)31. – eli

1

假設你有一個叫sentence字符串:敏捷的棕色狐狸跳過了懶狗。,並且您想要查找「the」的最後一次出現,名爲token

sentence.length = 44token.length = 3

考慮這個有點的java僞代碼:

public static int lastIndexOf(String sentence, String token) { 
    //The starting index is the first possible location your token could fit 
    int startingIndex = sentence.length() - token.length(); 
    //move backwards one character at a time until you reach 0 
    //checking for string fragment that equals your token at each iteration 
    for (int i = startingIndex; i >= 0; i--) { 
     String fragment = sentence.substring(i, i + token.length()); 
     if (fragment.equals(token)) return i; 
    } 
    return -1; 
} 

EDIT

以下是完整的應用程序僅使用長度和的charAt():

public class HelloWorld 
{ 
    // arguments are passed using the text field below this editor 
    public static void main(String[] args) 
    { 
    int indexOf = lastIndexOf("The quick brown fox jumps over the lazy dog.", "the"); 
    System.out.print(indexOf); 
    } 

    public static int lastIndexOf(String sentence, String token) { 
    int startingIndex = sentence.length() - token.length(); 
    for (int i = startingIndex; i >= 0; i--) { 
     String fragment = substring(sentence, i, i + token.length()); 
     if (strEquals(token, fragment)) return i; 
    } 
    return -1; 
    } 

    public static String substring(String str, int startingIndex, int endingIndex) { 
    int size = endingIndex - startingIndex; 
    char[] arr = new char[size]; 

    for (int i = 0; i < size; i++) { 
     arr[i] = str.charAt(startingIndex+i); 
    } 
    return new String(arr); 
    } 

    public static boolean strEquals(String s1, String s2) { 
    if (s1.length() != s2.length()) return false; 

    for (int i = 0; i < s1.length(); i++) { 
     if (s1.charAt(i) == s2.charAt(i)) continue; 
     return false; 
    } 

    return true; 
    } 
} 

編輯2

您在讀取輸入的方式中也有一個錯誤。您需要使用input.readLine()才能獲得完整的產品線。 input.read在空格上打破。沿着這些路線,您還需要爲每一條想要閱讀的行添加一個新的掃描儀。

編輯3

這裏是整個源:

import java.util.Scanner; 

public class HelloWorld { 
    public static void main(String[] args) 
    { 
     Scanner input1 = new Scanner(System.in); 
     System.out.println("\nEnter a choice: "); 
     String s1=""; 
     String s2=""; 
     int choice = input1.nextInt(); 
     if(choice == 1) { 
      Scanner input2 = new Scanner(System.in); 
      System.out.println("Enter first string: "); 
      s1 = input2.nextLine(); 
      Scanner input3 = new Scanner(System.in); 
      System.out.println("Enter second string: "); 
      s2 = input3.nextLine(); 
     } 

    int indexOf = lastIndexOf(s1, s2); 
    System.out.println(indexOf); 
    } 

    public static int lastIndexOf(String sentence, String token) { 
    int startingIndex = sentence.length() - token.length(); 
    for (int i = startingIndex; i >= 0; i--) { 
     String fragment = substring(sentence, i, i + token.length()); 
     if (strEquals(token, fragment)) return i; 
    } 
    return -1; 
    } 

    public static String substring(String str, int startingIndex, int endingIndex) { 
    int size = endingIndex - startingIndex; 
    char[] arr = new char[size]; 

    for (int i = 0; i < size; i++) { 
     arr[i] = str.charAt(startingIndex+i); 
    } 
    return new String(arr); 
    } 

    public static boolean strEquals(String s1, String s2) { 
    if (s1.length() != s2.length()) return false; 

    for (int i = 0; i < s1.length(); i++) { 
     if (s1.charAt(i) == s2.charAt(i)) continue; 
     return false; 
    } 

    return true; 
    } 
} 
+0

當然,但我不允許使用除charAt和length之外的內置字符串 方法。 – f1r4tc

+0

當然,但不是這個代碼返回s2的第一個索引?因爲它爲'句子'返回'-1':_快速的棕色狐狸跳過懶惰的狗。謝謝你的方式。 – f1r4tc

+0

非常感謝你,但是當你在'int indexOf = lastIndexOf(sentence,token)中手工輸入輸入時,它會返回-1。 System.out.print(indexOf);'for'sentence' =快速的棕色狐狸跳過懶狗。如何獲得lastindexof? – f1r4tc

1

我認爲這將歸結爲通過字符串中的字符循環和存儲發生比賽的最後一個索引。 這裏是不完美的,但簡單的例子無indexOf使用:

所有的
public static int contains(String s1, String s2) { 
    if(s1.length() < s2.length()) 
     return -1; 

    int lastOccurrence = -1; 
    for (int i = 0; i < s1.length();) { 
     if (s1.startsWith(s2, i)) { 
      lastOccurrence = i + s2.length() - 1; 
      i = lastOccurrence + 1; 
     } 
     else { 
      ++i; 
     } 
    } 
    return lastOccurrence; 
} 
相關問題