Filter a string array from another one
i m little bit confused related to string function I have one array of string Example
String Array1[]=new String[10];
Arra开发者_运维百科y1[0]="Hello";
String Array2[]=new String[10];
Array2[0]="Hello my world";
Array2[1]="Hi buddy";
I want to filter the string Array1[0] from Array2 That is, in which index of Array2 the string "Hello" appears.
/**
* This method searches for key in the array of String , starts looking from fromIndexSpecified
* @param source
* @param key
* @param fromIndex
* @return
*/
private static int findIndexOfKey(String[] source, String key, int fromIndex) {
if (fromIndex > source.length) {
return -1;// invalid arg ..can also throw IlligleArgumentException
}
for (int index = fromIndex; index < source.length; index++) {
if (source[index].indexOf(key) > -1) {
return index;//found..!
}
}
return -1; //no match found
}
You would need to loop through the items in Array2 and do a substring comparison:
private int findIndexOfSubstring(array, target) {
for (int i=0; i<array.size(); i++) {
if array[i].indexOf(target)>-1 return i; //element of Array2 contains target in it.
}
return -1; //no match found
}
//somewhere else
String Array1[]=new String[10];
Array1[0]="Hello";
String Array2[]=new String[10];
Array2[0]="Hello my world";
Array2[1]="Hi buddy";
int answer = findIndexOfSubstring(Array2, Array1[0]);
A String[]
is actually an Array of Strings. So it can hold multiples Strings.
For example:
String[] stringArray = new String[2];
stringArray[0] = "My String 1";
stringArray[1] = "My String 2";
If you want to find out the first index of an String array that contains a substring you need to do something like:
int findFirst(String subString, String[] stringArray) {
for (int i = 0; i < stringArray.length; i++) {
if (stringArray[i].contains(subString)) {
return i;
}
}
// indicates that no String in the array contained the subString
return -1;
}
And here is the way to use the method:
int firstIndex = findFirst("String 2", stringArray);
Iterate over the second array, check every time:
for(int i = 0; i < Array2.length; i++) {
if(Array2[i].contains(Array1[0]) {
//your logic here
System.out.println("Found match at position " + i);
}
}
Edit: be sure that in your given case Null-Pointer-Exceptions can occur. Perhaps add
if(Array2[i] != null)
You can use the method indexOf
from Apache Commons ArrayUtils class.
Usage:
String[] array1 = new String[10];
array1[0] = "Hello";
String[] array2 = new String[10];
array2[0] = "Hello my world";
array2[1] = "Hi buddy";
int index = ArrayUtils.indexOf(array2, array1[0]);
精彩评论