Skip to main content

Simple one regarding partial comparison of strings

2 replies [Last post]
manchesterssago
Offline
Joined: 2008-05-02

Hello

I am trying to create a search which evaluates part of a string. EG matching the author surname "simpson" would give books by joe simpson and john simpson.

Whats the simplest way of doing this?

thanks in advance
tom

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tarbo
Offline
Joined: 2006-12-18

The simplest way to do this in terms of code would be to use [url=http://java.sun.com/javase/6/docs/api/java/lang/String.html#contains(java.lang.CharSequence)]String.contains(CharSequence)[/url], and to iterate over all the fields you want to search. For instance:

[code]List byAuthor(String partialName) {
List rv = ...;
for (Book book : allBooks) {
if (book.getAuthorName().contains(partialName)) {
rv.add(book);
}
}
return rv;
}[/code]

The simplest way in terms of processing speed would probably be using [url=http://en.wikipedia.org/wiki/Suffix_tree]suffix trees[/url]. There are almost certainly very decent Java implementations of suffix trees abound or, if not or if you need the exercise, you can write your own and learn from the experience. ;)

Note that all this deals with [i]exact[/i] matches. To be case-insensitive, it would be easiest to store authors' names in the same case (lower or upper) and convert search strings to this case; otherwise, you run the risk of a search for "simpson" not matching "Simpson".

Inexact or fuzzy matching is a research domain on its own.

Hope this helps,
Jonathan

manchesterssago
Offline
Joined: 2008-05-02

works a treat, thank you