集册 Java实例教程 字符串搜索方法indexOf和lastIndexOf。

字符串搜索方法indexOf和lastIndexOf。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

569
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
字符串搜索方法indexOf和lastIndexOf。

public class Main //来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

{

   public static void main(String[] args)

   {

      String letters = "abcdefghijklmabcdefghijklm";


      // test indexOf to locate a character in a string

      System.out.printf(

         "'c' is located at index %d\n", letters.indexOf('c'));

      System.out.printf(

         "'a' is located at index %d\n", letters.indexOf('a', 1));

      System.out.printf(

         "'$' is located at index %d\n\n", letters.indexOf('$'));


      // test lastIndexOf to find a character in a string

      System.out.printf("Last 'c' is located at index %d\n",

         letters.lastIndexOf('c'));

      System.out.printf("Last 'a' is located at index %d\n",

         letters.lastIndexOf('a', 25));

      System.out.printf("Last '$' is located at index %d\n\n",
      /*
      nowjava.com - 时代Java
      */

         letters.lastIndexOf('$'));


      // test indexOf to locate a substring in a string

      System.out.printf("\"def\" is located at index %d\n", 

         letters.indexOf("def"));

      System.out.printf("\"def\" is located at index %d\n",

         letters.indexOf("def", 7));

      System.out.printf("\"hello\" is located at index %d\n\n",

         letters.indexOf("hello"));


      // test lastIndexOf to find a substring in a string

      System.out.printf("Last \"def\" is located at index %d\n",

     
展开阅读全文