0

I have a string array. For example:

["Tartrazine","Orange GGN", "Riboflavin-5-Phosphate"]

And I have a string. For example:

"Riboflvin"

I want to look for most similar string in the array and get it if it exists. So I need this output:

"Riboflavin-5-Phosphate"

But if the array looks like this:

["Tartrazine","Orange GGN", "Quinoline"]

I want something like this output:

"No similar strings found"

I tried using FuzzyWuzzy library, but it shows a lot of false alarms.

2 Answers2

3

You can use String#contains method, sequentially reducing the length of the string to search if the full string is not found:

String[] arr = {"Tartrazine", "Orange GGN", "Riboflavin-5-Phosphate"};
String element = "Riboflvin";

boolean found = false;
for (int i = 0; i < element.length(); i++) {
    // take shorter substring if nothing found at previous step
    String part = element.substring(0, element.length() - i);
    // if any string from array contains this substring
    if (Arrays.stream(arr).anyMatch(str -> str.contains(part))) {
        System.out.println("Found part: " + part);
        // then print these strings one by one
        Arrays.stream(arr).filter(str -> str.contains(part))
                .forEach(System.out::println);
        found = true;
        break;
    }
}
// if nothing found
if (!found) {
    System.out.println("No similar strings found");
}

Output:

Found part: Ribofl
Riboflavin-5-Phosphate
1

Well, it depends what you want to do exactly.

There are a couple of things you can do you can check wether the array contains an exact match of the String you are looking for by just calling list.contains("yourStr") the list directly. You could also check each value to see whether it contains a certain substring like so:

foreach(String s : list) {
    if (s.contains(subStr) {
        return s;
    }
}

Otherwise, if you really would like to check similarity it becomes a bit more complicated. Then we really have to answer the question: "how similar is similar enough?". I guess this post as a decent answer to that problem: Similarity String Comparison in Java

Edwin
  • 33
  • 6