something like equalsIgnoreCase while using indexOf - java

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

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;
}

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());
}
}

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());

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());

Related

Returning an empty String instead of null

public class Test {
public static String MakeSequence(int N)
{
int j;
N=5;
for (N=5;N>=1;--N)
{
for(j=1;j<N+1;++j)
{
return MakeSequence(5);
}
}
if (N<1)
{
String x = "";
System.out.println(x.isEmpty());
}
}
}
I want to return the sequence 555554444333221 when N=5 and return an empty string if the input parameter N is less than 1, but I'm not sure how to modify the code I made
Be simple and do not add additional checks:
public static String makeSequence(int N) {
StringBuilder buf = new StringBuilder();
while (N > 0) {
buf.append(String.valueOf(N).repeat(N));
N--;
}
return buf.toString();
}
public class Test {
public static String makeSequence(int n) {
String value = " ";
for (int i = n; i >= 1; --i) {
for (int j = 1; j < i + 1; ++j) {
value+= i;
}
}
return value;
}
public static void main(String[] args) {
final String s = makeSequence(5);
System.out.println(s);
}
}
In your code, you always try to assign 5 instead of considering the value send to the method. Above solution returns the sequence and if the parameter N(in code I use n) is less than 1 then returns the empty string.
FYI: As a best practice we start both variable and method names in simple letters.

How to check if string contains some character in Java?

I want to check for instance if string "ABCD" contains "DC" string in it in Java. But this is not a substring example, because every time my string and checking characters will change. and I store checking characters into an array, So substring failed, it only works if I have CD, or BC. and I couldn't do match since every time I call checking character from an array. SO what should I do any suggestion
here's some pseudocode to get you started
we'll call "ABCD" the source string and "DC" the target string
change source string to list of chars
change target string to list of chars
for each char in target list of char
if source list does not contain target char
return false;
return true
I use this method for char and byte array. After you got the index of the src array where the sub is matched with, you then can store it anywhere you want.
Try this:
public static int indexOf(char[] src, char[] sub) {
int limit = src.length - sub.length;
int i, j;
for(i = 0; i < limit +1; ++i) {
for(j = 0; j < sub.length; ++j) {
if (src[i+j] != sub[j]) {
break;
}
}
if (j == sub.length)
return i;
}
return -1;
}
Get all the permutation of the source string till it contains the desired sub string
Permutation Logic based on
public static void main(String[] args) {
System.out.println(Test.checkIfContains("ABCD", "DC"));
}
public static Boolean checkIfContains(String main, String check) {
return permutation("", main, check);
}
private static Boolean permutation(String prefix, String main, String check) {
int n = main.length();
if (n == 0) {
if (checkFor(prefix, check)) {
return true;
}
} else {
for (int i = 0; i < n; i++) {
if (permutation(prefix + main.charAt(i), main.substring(0, i) + main.substring(i + 1, n), check)) {
return true;
}
}
}
return false;
}
private static boolean checkFor(String prefix, String check) {
return prefix.contains(check);
}
As I understand it, you want to see if all of the characters of the second string (which I called checkString) are contained in the first string (refString). I would proceed using a function like this
private boolean checkString(String refString, String checkString) {
boolean a;
for (int i; i < checkString.length(); i++) {
for (int j; j < refString.length(); j++) {
a |= checkString.charAt(i) == refString.charAt(j);
}
if (!a) return false;
}
return true;
}
Which return true only when all the characters in checkString are in the reference string.

matching a letter with a word

I've the below code.
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Dummy {
public static void main(String args[]) throws Exception {
String word="hi";
String[] one={"a","b","c"};
String[] two={"d","e","f"};
String[] three={"g","h","i"};
String[] four={"j","k","l"};
String[] five={"m","n","o"};
String[] six={"p","q","r","s"};
String[] seven={"t","u","v"};
String[] eight={"w","x","y","z"};
for(int i=0;i<word.length();i++)
{
for(int j=0;j<three.length;j++)
{
if(three[j].equals(word.charAt(i)))
{
System.out.println("Matched");
}
else
{
System.out.println("err");
}
}
}
}
}
Here my concept is to match a letter from the string to the array created and here the output is all err(condition stating not matched). please let me know where am i going wrong.
Thanks
You're comparing a single-character string (from your arrays) to a character. Make your arrays of char, not String. (And use == to compare them.)
The element three[j] in for loop is String whereas word.charAt(i) is char.. so equals() against those will be always false.
You should either change it to
if(three[j].equals(String.valueOf(word.charAt(i))))
so that it compares string's actual context, or define arrays (one, two, three.. ) to be char array instead of string array so that you can simply use == for that.
Please check equals() for String, Object, and the others in JavaDoc, and probably you need to check hashCode() as well to fully understand what's equals() means in Java.
charAt return a char not a string so it can't be "equals" to a String
Why don't you use String.indexOf() ?
for(int j=0;j<three.length;j++)
{
if(word.indexOf(three[j]) == -1)
{
System.out.println("err");
}
else
{
System.out.println("Matched");
}
}
This way you will enter in a single loop..
Try like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < one.length; i++) {
result.append(one[i]);
}
if (result.toString().equals(word)) {
System.out.println("Matched");
} else {
System.out.println("err");
}
Just saying the obvious....sometimes it is helpful to see the actual code. Following is excerpt from java.lang.String
See bold condition in particular. it returns false if instanceof fails!
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (**anObject instanceof String**) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}

Find substring in List and return Index Number

I have an List, with Strings like:
String One
String Two
String Three
Now i would like to get the Index Number for the Substring "One". How can i get this?
I only could make it if i convert it to an Array and then:
public static int findInArray(Object[] arr, String searchName) {
int i;
for (i=0; i<arr.length; i++ ) {
String test = arr[i].toString();
if (test.contains(searchName)) {
//System.out.println("Substring found in:"+i);
break;
}
}
return i;
}
Isn't there a way to search for the Substring without converting it to an Array?
List already contains indexes
for(int i=0;i<list.size();++i){
if (list.get(i).contains("searchString")) {
System.out.println("Substring found in:"+i);
}
}
public static int find(List<String> list, String searchString) {
for(int i=0 ; i < list.size() ; ++i){
if (list.get(i).contains(searchString)) {
return i;
}
}
return -1;
}
Try this way, and you can get its index, or return -1 indicating not found.
public static int findInList(List<String> list, String searchName) {
for(String str : list){
if(str.indexOf(searchName) > -1){
//System.out.println("Substring found in:"+i);
return list.indexOf(str);
}
}
return -1;
}

Searching for a string within an array

Below I am trying to create a method which searches through an array for a certain string and returns the position of it, if not there then -1 should be the number returned. Below I search for a word using the method and it returns -1 even though the word is within the array. Why is this?
String answer = "";
System.out.println("Enter word to search within array");
answer = in.next();
public static int search(String[] theWords, String answer) {
int a = -1;
for(int i = 0; i < theWords.length; i++) {
if (answer.equals(theWords[i])){
a = i;
break;
}
}
return a;
}
I can't see anything wrong with the code, but I would recommend eliminating the local variable that holds the return value:
public static int Search(String[] thewords, String answer) {
for (int i = 0; i < thewords.length; i++) {
if (answer.equals(thewords[i])){
return i;
}
}
return -1;
}
With this simplified logic, there's little or no chance of there being a bug in this code.
I assume this is course work, and you are not allowed to use library methods. If you were allowed, your method could be a single line:
return Arrays.asList(theWords).indexOf(answer);
You can optionally make a copy of the array since sorting might be unwanted for consumers of the method
public static int Search(String[] thewords, String answer) {
if(thewords == null) {
throw new NullPointerException();
}
String[] copy = new String[thewords.length];
System.arraycopy(thewords,0,copy,0,copy.length);
Arrays.sort(thewords);
return Arrays.binarySearch(thewords, answer);
}
Note: It returns -pos and not -1
If you need -1:
public static int Search(String[] thewords, String answer) {
if(thewords == null) {
throw new NullPointerException();
}
String[] copy = new String[thewords.length];
System.arraycopy(thewords,0,copy,0,copy.length);
Arrays.sort(thewords);
int idx = Arrays.binarySearch(thewords, answer);
return idx < 0? -1:idx;
}
Concerning your code: I believe the problem would be related to casing or spacing:
Replace with something like: if (answer.equalsIgnoreCase(theWords[i].trim())){
For large arrays go with binary search.

Categories