How to map character to numeric position in java?

前端 未结 7 1950
忘了有多久
忘了有多久 2020-11-30 06:26

E.g.

  • input: [\'A\', \'Z\', \'F\', \'D\', ...]
  • output: [0, 25, 5, 3, ...]

In C I\'d just subtract the char from \'A\', but I don\'t seem

7条回答
  •  暖寄归人
    2020-11-30 06:47

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

提交回复
热议问题