Java 获取元素在数组中的位置
在Java 中如何获取元素在数组中的位置呢?
(1)
- /***
- * 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;
- }
测试:
- @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)
- /***
- * times byte occure int byte[]
- *
- * @param hexStr
- * @param keyWord
- * @return
- */
- 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());
- }