Reputation: 24012
I am using this code, to get the index of a String in an Array.
int n = Arrays.asList(Names).indexOf(textBox.getText());
The problem here is, if the String in textBox is different in case to its similar String in the Array. It returns -1. How can make it something like equalsIgnoreCase in case of String comparision.
Thank You
Upvotes: 5
Views: 6141
Reputation: 41220
A different approach where internally make sure ignore case.
public static int indexOfIgnoreCase(String[] strs, String text){
int n = strs.length;
for(int i=0;i<n;i++){
if(strs[i].equalsIgnoreCase(text))
return i;
}
return -1;
}
int n = indexOfIgnoreCase(Names,textBox.getText());
Upvotes: 1
Reputation: 5183
You can use StringUtils class of Apache commons libraries or this If you don't want to download the library look at the source code for logic to create the method. The stackoverflow link for using StringUtils
If you want to find the index of String from array of strings then there is another library ArrayUtils which has a method indexOf
here's the implementation of indexOf
public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
since you can see that it uses .equals() I suggest you to
1) create a custom string class
2) add it to the array
3) override the .equals method like this
class StringCustom
{
String string;
//implement getters and setters
public String equals(Object o)
{
return this.getString().equalsIgnoreCase(((String)o).getString());
}
}
Upvotes: 3
Reputation: 7357
You can use the Collator class. in Here you can set different levels for your comparison. you can ignore lower and upper cases, and set some specific language charackters. In German for example it can set ß equal to ss.
here´s some documentary: Collator class
Edit : here´s an example Code for you
private int indexOf(String[] original, String search) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.SECONDARY);
for(int i = 0;i<original.length;++i) {
if(collator.equals(search, original[i]))
return i;
}
return -1;
}
Upvotes: 3
Reputation: 9579
You can extend ArrayList
in this way
public class StringArrayList extends ArrayList<String> {
@Override
public boolean contains(Object o) {
String paramStr = (String)o;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return true;
}
return false;
}
public int indexOf(Object o) {
String paramStr = (String)o;
int index = 0;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return index;
index++;
}
return -1;
}
}
Eventually :
int n = new StringArrayList(Arrays.asList(Names)).indexOf(textBox.getText());
Upvotes: 0