要获取一个字符串在字符串数组中的序号,可以使用 Java 中的 Arrays 类 的静态方法 binarySearch() 来实现。该方法会返回指定元素在指定数组中的索引位置。

以下是一个示例代码:

String[] array = {'apple', 'banana', 'orange', 'pear'};
String target = 'orange';

// 使用 binarySearch 方法获取字符串在数组中的序号
int index = Arrays.binarySearch(array, target);

if (index >= 0) {
    System.out.println('字符串在数组中的序号为:' + index);
} else {
    System.out.println('字符串不在数组中');
}

输出结果为:

字符串在数组中的序号为:2

需要注意的是,binarySearch() 方法要求数组必须是有序的。如果数组无序,可以使用 Arrays 类的 sort() 方法对数组进行排序再使用 binarySearch() 方法。

另外,如果字符串不在数组中,binarySearch() 方法会返回一个负数,表示如果要将该字符串插入数组中的话,应该插入的位置。所以在判断返回值时需要进行非负判断。

希望对你有帮助!

Android 获取字符串在数组中的序号 - Java BinarySearch 方法

原文地址: https://www.cveoy.top/t/topic/pZfr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录