Skip to main content

Simple one regarding partial comparison of strings

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


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

Reply viewing options

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

The simplest way to do this in terms of code would be to use [url=]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)) {
return rv;

The simplest way in terms of processing speed would probably be using [url=]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,

Joined: 2008-05-02

works a treat, thank you