1

注意:这个问题是针对学校作业提出的。我跌倒了,我正在接近真正的代码,只剩下几点需要注意了。

我被要求编写一个接收两个字符串(s1 和 s2)并检查 s2 是否区分大小写的方法。如果 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 = aabbccbbe和的输出s2 = bb2

编辑: @eli 的代码

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;
    }
4

3 回答 3

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;
}

编辑

这是仅使用长度和 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;
  }
}
于 2016-11-22T20:03:20.857 回答
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;
}
于 2016-11-22T20:19:34.650 回答
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;
}

这里解释了正则表达式模式。

find()您一起确保至少出现一次。由于该模式可以产生 1 个且只有 1 个结果,因此您可以在匹配器中请求“第一次出现的第一个索引”,使用start().

编辑 好的,我可以看到你不能使用除了charAtand之外的任何东西length。这是一个没有正则表达式、子字符串、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;
}

我必须承认我没有彻底测试这一点。

最后 我为你做了一些小的修复。我不知道您如何能够编译您在帖子中编辑的内容。这是一个工作示例:

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;
    }
}
于 2016-11-22T20:51:33.857 回答