Guava – Chars.lastIndexOf()方法与实例

Guava Chars.lastIndexOf()方法与实例

Guava库中Chars类的lastIndexOf()方法用于查找char数组中给定char值的最后索引。这个要搜索的char值和要搜索的char数组,都作为参数传递给这个方法。它返回一个整数值,这个整数值是指定的char值的最后索引。如果没有找到该值,它将返回-1.

语法:

public static int lastIndexOf(char[] array,
                              char target)

参数: 该方法接受两个强制性的参数:

  • array: 是char值的数组,其中char值将被搜索到.
  • target: 这是要在char数组中搜索最后一个索引的char值.

返回值:该方法返回一个整数值,它是指定char值的最后一个索引。如果没有找到该值,它将返回-1。

下面的程序说明了这个方法:

示例1:

// Java code to show implementation of
// Guava's Chars.lastIndexOf() method
  
import com.google.common.primitives.Chars;
import java.util.Arrays;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a char array
        char[] arr = { 'a', 'b', 'c', 'd',
                       'b', 'c', 'b', 'd' };
  
        char target = 'b';
  
        // Using Chars.lastIndexOf() method
        // to get the index of last appearance
        // of a given element in array
        // and return -1 if element is
        // not found in the array
        int index
            = Chars.lastIndexOf(arr, target);
  
        if (index != -1) {
            System.out.println("Target is present"
                               + " at index "
                               + index);
        }
        else {
            System.out.println("Target is not present"
                               + " in the array");
        }
    }
}

输出:

Target is present at index 6

示例2:

// Java code to show implementation of
// Guava's Chars.lastIndexOf() method
  
import com.google.common.primitives.Chars;
import java.util.Arrays;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // Creating a char array
        char[] arr = { 'a', 'b', 'c', 'd',
                       'b', 'c', 'b', 'd' };
  
        char target = 'z';
  
        // Using Chars.lastIndexOf() method
        // to get the index of last appearance
        // of a given element in array
        // and return -1 if element is
        // not found in the array
        int index
            = Chars.lastIndexOf(arr, target);
  
        if (index != -1) {
            System.out.println("Target is present"
                               + " at index "
                               + index);
        }
        else {
            System.out.println("Target is not present"
                               + " in the array");
        }
    }
}

输出:

Target is not present in the array

参考:[https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#lastIndexOf(char[], %20char)](https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#lastIndexOf(char[], char))

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程