繁体   English   中英

不使用lastIndexOf方法在字符串中打印字符串的最后一个索引

[英]Printing last index of string in a string without using lastIndexOf method

注意:这个问题被要求进行学校作业。 我摔倒了,我正在接近真正的代码,只剩下几点需要处理。

我被要求编写一个接收两个字符串(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

编辑: @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;
    }

假设你有一个叫做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;
}

编辑

以下是仅使用length和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;
  }
}

我认为它将归结为循环字符串字符并存储发生匹配的最后一个索引。 这里不完美,但不使用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;
}

首先,关闭您完成后打开的所有资源。

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()实现。

编辑好吧,我可以看到除了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;
}

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

最后我已经为你做了一些小修复。 我不知道你是如何编写你在帖子中编辑的内容的。 这是一个工作样本:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM