杰瑞科技汇

Java中lastIndexOf()方法怎么用?

Of course! Let's dive deep into the lastIndexOf method in Java. It's a very useful string method for finding the position of a character or a substring within a string, starting from the end.

Java中lastIndexOf()方法怎么用?-图1
(图片来源网络,侵删)

Overview

The String.lastIndexOf() method in Java is used to find the last occurrence of a specified character or substring within a given string. It's the opposite of indexOf(), which finds the first occurrence.

There are two main overloaded versions of this method:

  1. lastIndexOf(int ch): Finds the last occurrence of a single character.
  2. lastIndexOf(String str): Finds the last occurrence of a substring.

There are also two more versions that allow you to specify a starting index for the search:

  1. lastIndexOf(int ch, int fromIndex): Finds the last occurrence of a character, starting the search from the specified index and moving backward.
  2. lastIndexOf(String str, int fromIndex): Finds the last occurrence of a substring, starting the search from the specified index and moving backward.

lastIndexOf(int ch): Finding the Last Character

This method searches the string and returns the index of the last time the specified character appears.

Java中lastIndexOf()方法怎么用?-图2
(图片来源网络,侵删)

Syntax

public int lastIndexOf(int ch)

Parameters

  • ch: A char value (passed as an int due to Java's method overloading rules). It's the character to search for.

Return Value

  • The index of the last occurrence of the character.
  • -1 if the character is not found in the string.

Example

public class LastIndexOfExample {
    public static void main(String[] args) {
        String sentence = "This is a simple example sentence.";
        // Find the last index of the character 's'
        int lastIndex = sentence.lastIndexOf('s');
        System.out.println("The original string is: \"" + sentence + "\"");
        System.out.println("The last index of 's' is: " + lastIndex); // Output: 20
        // Try to find a character that doesn't exist
        int notFoundIndex = sentence.lastIndexOf('z');
        System.out.println("The last index of 'z' is: " + notFoundIndex); // Output: -1
    }
}

lastIndexOf(String str): Finding the Last Substring

This method searches the string and returns the starting index of the last time the specified substring appears.

Syntax

public int lastIndexOf(String str)

Parameters

  • str: The substring to search for.

Return Value

  • The starting index of the last occurrence of the substring.
  • -1 if the substring is not found in the string.

Example

public class LastIndexOfSubstringExample {
    public static void main(String[] args) {
        String text = "Java is fun, and Java is powerful.";
        // Find the last index of the substring "Java"
        int lastIndex = text.lastIndexOf("Java");
        System.out.println("The original string is: \"" + text + "\"");
        System.out.println("The last index of 'Java' is: " + lastIndex); // Output: 20
        // Try to find a substring that doesn't exist
        int notFoundIndex = text.lastIndexOf("Python");
        System.out.println("The last index of 'Python' is: " + notFoundIndex); // Output: -1
    }
}

lastIndexOf(int ch, int fromIndex): Searching Backwards from an Index

This is a very powerful version. It searches backward from the specified fromIndex to find the last occurrence of the character.

Syntax

public int lastIndexOf(int ch, int fromIndex)

Parameters

  • ch: The character to search for.
  • fromIndex: The index to start the search from. The search will move backwards from this index (towards the beginning of the string).

Return Value

  • The index of the character found.
  • -1 if the character is not found in the search range.

Example

Imagine the string: "hello world". The character 'l' is at index 2 and 3. If we search for 'l' starting from index 3, we find it at index 3. If we search for 'l' starting from index 2, we find it at index 2.

public class LastIndexOfFromIndexExample {
    public static void main(String[] args) {
        String word = "hello world";
        System.out.println("The original string is: \"" + word + "\"");
        System.out.println("String indexes: 012345678901");
        // Search for 'l' starting from index 5 (searches 'o worl')
        int index1 = word.lastIndexOf('l', 5);
        System.out.println("Searching for 'l' from index 5: " + index1); // Output: 3
        // Search for 'l' starting from index 2 (searches 'hel')
        int index2 = word.lastIndexOf('l', 2);
        System.out.println("Searching for 'l' from index 2: " + index2); // Output: 2
        // Search for 'l' starting from index 1 (searches 'h')
        int index3 = word.lastIndexOf('l', 1);
        System.out.println("Searching for 'l' from index 1: " + index3); // Output: -1
    }
}

lastIndexOf(String str, int fromIndex): Searching for a Substring Backwards from an Index

This is the most complex version. It searches backward from fromIndex to find the last occurrence of the substring.

Java中lastIndexOf()方法怎么用?-图3
(图片来源网络,侵删)

Syntax

public int lastIndexOf(String str, int fromIndex)

Parameters

  • str: The substring to search for.
  • fromIndex: The index to start the search from. The search will move backwards.

Return Value

  • The starting index of the substring found.
  • -1 if the substring is not found in the search range.

Example

Let's use the string "abababab". The substring "aba" appears at index 0 and 2 and 4.

public class LastIndexOfSubstringFromIndexExample {
    public static void main(String[] args) {
        String text = "abababab";
        System.out.println("The original string is: \"" + text + "\"");
        System.out.println("String indexes: 01234567");
        // Search for "aba" starting from index 6 (searches "babab")
        // The last "aba" in this range starts at index 4.
        int index1 = text.lastIndexOf("aba", 6);
        System.out.println("Searching for 'aba' from index 6: " + index1); // Output: 4
        // Search for "aba" starting from index 3 (searches "abab")
        // The last "aba" in this range starts at index 2.
        int index2 = text.lastIndexOf("aba", 3);
        System.out.println("Searching for 'aba' from index 3: " + index2); // Output: 2
        // Search for "aba" starting from index 1 (searches "aba")
        // The last "aba" in this range starts at index 0.
        int index3 = text.lastIndexOf("aba", 1);
        System.out.println("Searching for 'aba' from index 1: " + index3); // Output: 0
    }
}

Key Points to Remember

  • Case-Sensitive: lastIndexOf is case-sensitive. 'A' is not the same as 'a'.
    "Java".lastIndexOf("j"); // Returns -1
  • Return Value on Not Found: Always check for -1 to see if the character/substring was found. Trying to use the index when it's -1 will lead to StringIndexOutOfBoundsException if you try to access the string with it.
  • Search Direction: When a fromIndex is provided, the search always goes backwards from that index towards the start of the string (index 0).
  • Empty String (): Searching for an empty string () will always return the fromIndex if provided, or the length of the string otherwise. This is consistent with how indexOf behaves.
    "hello".lastIndexOf(""); // Returns 5
    "hello".lastIndexOf("", 2); // Returns 2

Common Use Case: Extracting a File Extension

A very practical use of lastIndexOf is to find the extension of a file name.

public class FileExtensionExample {
    public static void main(String[] args) {
        String fileName = "my.document.final.report.pdf";
        // Find the last dot
        int dotIndex = fileName.lastIndexOf('.');
        // Check if a dot was found
        if (dotIndex != -1) {
            // The extension is the substring from the dot + 1 to the end
            String extension = fileName.substring(dotIndex + 1);
            System.out.println("File name: " + fileName);
            System.out.println("Extension: " + extension); // Output: pdf
        } else {
            System.out.println("The file has no extension.");
        }
    }
}
分享:
扫描分享到社交APP
上一篇
下一篇