天天看点

Java 获取元素在数组中的位置

(1)

Java 获取元素在数组中的位置

/*** 

     * get location of element in a array 

     * @param arr : a array 

     * @param value2 : element of array 

     * @return 

     */  

    public static int indexofarr(string[] arr,string value2){  

        if(valuewidget.isnullorempty(arr)){  

            return systemhwutil.negative_one;  

        }  

        for(int i=0;i<arr.length;i++){  

            if(arr[i].equals(value2)){  

                return i;  

            }else{//做了容错,不是完全匹配  

                if(value2.startswith(arr[i])){  

                    return i;  

                }  

            }  

        return systemhwutil.negative_one;  

    }  

Java 获取元素在数组中的位置

 测试:

Java 获取元素在数组中的位置

@test  

    public void test_indexof(){  

        string[]arr=new string[]{"a","b","c","d"};  

//      system.out.println(systemhwutil.indexofarr(arr, "d"));  

        org.junit.assert.assertequals(3, systemhwutil.indexofarr(arr, "d"));  

 注意:位置是从零开始的.

(2)

Java 获取元素在数组中的位置

     * times byte occure int byte[] 

     *  

     * @param hexstr 

     * @param keyword 

    public static int indexof(string hexstr, string keyword) {  

        return hexstr.indexof(keyword.tolowercase()) / 2;  

    public static int indexof(byte[] bytes, string keyword) {  

        return indexof(systemhwutil.tohexstring(bytes), keyword.tolowercase());  

    public static int indexof(byte[] bytes, byte[] keyword) {  

        return indexof(systemhwutil.tohexstring(bytes), systemhwutil  

                .tohexstring(keyword).tolowercase());