E.g.
In C I\'d just subtract the char from \'A\', but I don\'t seem
Here's different implementation which runs in logarithmic time:
Class
import java.util.Arrays;
import java.util.Collections;
public class CharacterIndex {
private char[] characters = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public int index(char character) {
assert characters != null;
return Arrays.binarySearch(characters, Character.toUpperCase(character));
}
}
Unit Test
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class CharacterIndexTest {
private CharacterIndex characterIndex;
@Before
public void createIndex() {
characterIndex = new CharacterIndex();
}
@Test
public void testIndexOfLetterA() {
assertEquals(0, characterIndex.index('A'));
assertEquals(0, characterIndex.index('a'));
}
@Test
public void testNotALetter() {
assertEquals(-1, characterIndex.index('1'));
}
}