exercise7_3.java

来自「Introduction to java programming 一书中所有编程」· Java 代码 · 共 48 行

JAVA
48
字号
// Exercise7_3.java: Check whether the first string is a substring
// of the second string
import javax.swing.JOptionPane;

public class Exercise7_3 {
  public static void main(String[] args) {
    // Prompt the user to enter two strings
    String first = JOptionPane.showInputDialog(
      null, "Enter the first string:",
      "Exercise7_3 Input", JOptionPane.QUESTION_MESSAGE);

    String second = JOptionPane.showInputDialog(
      null, "Enter the second string:",
      "Exercise7_3 Input", JOptionPane.QUESTION_MESSAGE);

    if (isSubstring(first, second)) {
      System.out.println(first + " is a substring of " + second);
    }
    else {
      System.out.println(first + " is not a substring of " + second);
    }
  }

  /**Check if the first string is a substring of the second string*/
  public static boolean isSubstring(String first, String second) {
    int remainingLength = second.length();
    int startingIndex = 0;

    // Note toWhile is a label. You can use break with a label
    // attached.
    toWhile: while (first.length() <= remainingLength) {
      // What is wrong if the following line is used
      // for (int i=startingIndex; i<=first.length(); i++)
      for (int i = 0; i < first.length(); i++) {
        if (first.charAt(i) != second.charAt(startingIndex+i)) {
          startingIndex++;
          remainingLength--;
          continue toWhile;
        }
      }

      return true;
    }

    return false;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?