stringindexmethods.java

来自「金旭亮的java教案」· Java 代码 · 共 60 行

JAVA
60
字号
//StringIndexMethods.java
// This program demonstrates the String 
// class index methods.
import javax.swing.*;

public class StringIndexMethods {
   public static void main( String args[] )
   {
      String letters = "abcdefghijklmabcdefghijklm";
      String output;

      // test indexOf to locate a character in a string
      output = "'c' is located at index " +
               letters.indexOf( 'c' );

      output += "\n'a' is located at index " +
                letters.indexOf( 'a', 1 );	//第2个参数是开始查找的起始下标

      output += "\n'$' is located at index " +
                letters.indexOf( '$' );

      // test lastIndexOf to find a character in a string
      output += "\n\nLast 'c' is located at index " +
                letters.lastIndexOf( 'c' );

      output += "\nLast 'a' is located at index " +
                letters.lastIndexOf( 'a', 25 );

      output += "\nLast '$' is located at index " +
                letters.lastIndexOf( '$' );

      // test indexOf to locate a substring in a string
      output += "\n\n\"def\" is located at index " +
                letters.indexOf( "def" );

      output += "\n\"def\" is located at index " +
                letters.indexOf( "def", 7 );

      output += "\n\"hello\" is located at index " +
                letters.indexOf( "hello" );

      // test lastIndexOf to find a substring in a string
      output += "\n\nLast \"def\" is located at index " +
                letters.lastIndexOf( "def" );

      output += "\nLast \"def\" is located at index " +
                letters.lastIndexOf( "def", 25 );

      output += "\nLast \"hello\" is located at index " +
                letters.lastIndexOf( "hello" );

      JOptionPane.showMessageDialog( null, output,
         "Demonstrating String Class \"index\" Methods",
         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

⌨️ 快捷键说明

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