Better way to generate array of all letters in the alphabet

后端 未结 17 1922
说谎
说谎 2020-12-02 10:56

Right now I\'m doing

for (char c = \'a\'; c <= \'z\'; c++) {
    alphabet[c - \'a\'] = c;
}

but is there a better way to do it? Similar

相关标签:
17条回答
  • 2020-12-02 11:27
    static String[] AlphabetWithDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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", "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"};
    
    0 讨论(0)
  • 2020-12-02 11:27
    for (char letter = 'a'; letter <= 'z'; letter++)
    {
        System.out.println(letter);
    }
    
    0 讨论(0)
  • 2020-12-02 11:28

    In Java 8 with Stream API, you can do this.

    IntStream.rangeClosed('A', 'Z').mapToObj(var -> (char) var).forEach(System.out::println);
    
    0 讨论(0)
  • 2020-12-02 11:28

    Check this once I'm sure you will get a to z alphabets:

    for (char c = 'a'; c <= 'z'; c++) {
        al.add(c);
    }
    System.out.println(al);'
    
    0 讨论(0)
  • 2020-12-02 11:28

    Here are a few alternatives based on tom thomas' answer.

    Character Array:

            char[] list = IntStream.concat(
                    IntStream.rangeClosed('0', '9'),
                    IntStream.rangeClosed('A', 'Z')
            ).mapToObj(c -> (char) c+"").collect(Collectors.joining()).toCharArray();
    

    String Array:

    Note: Won't work correctly if your delimiter is one of the values, too.

            String[] list = IntStream.concat(
                    IntStream.rangeClosed('0', '9'),
                    IntStream.rangeClosed('A', 'Z')
            ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(",");
    

    String List:

    Note: Won't work correctly if your delimiter is one of the values, too.

            List<String> list = Arrays.asList(IntStream.concat(
                    IntStream.rangeClosed('0', '9'),
                    IntStream.rangeClosed('A', 'Z')
            ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(","));
    
    0 讨论(0)
  • 2020-12-02 11:29
    char[] alphabet = {'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'};
    
    0 讨论(0)
提交回复
热议问题