Better way to generate array of all letters in the alphabet

后端 未结 17 1924
说谎
说谎 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:40

    To get uppercase letters in addition to lower case letters, you could also do the following:

    String alphabetWithUpper = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".toUpperCase();
    char[] letters = alphabetWithUpper.toCharArray();
    
    0 讨论(0)
  • 2020-12-02 11:48

    If you are using Java 8

    char[] charArray = IntStream.rangeClosed('A', 'Z')
        .mapToObj(c -> "" + (char) c).collect(Collectors.joining()).toCharArray();
    
    0 讨论(0)
  • 2020-12-02 11:49

    with io.vavr

    public static char[] alphanumericAlphabet() {
        return CharSeq
                .rangeClosed('0','9')
                .appendAll(CharSeq.rangeClosed('a','z'))
                .appendAll(CharSeq.rangeClosed('A','Z'))
                .toCharArray();
    }
    
    0 讨论(0)
  • 2020-12-02 11:49
    import java.util.*;
    public class Experiments{
    
    
    List uptoChar(int i){
           char c='a'; 
            List list = new LinkedList();
             for(;;) {
               list.add(c);
           if(list.size()==i){
                 break;
               }
           c++;
                }
            return list;
          } 
    
        public static void main (String [] args) {
    
            Experiments experiments = new Experiments();
              System.out.println(experiments.uptoChar(26));
        } 
    
    0 讨论(0)
  • 2020-12-02 11:51

    This is a fun Unicode solution.

    char[] alpha = new char[26]
    for(int i = 0; i < 26; i++){
        alpha[i] = (char)(97 + i)
    }
    

    This generates a lower-cased version of alphabet, if you want upper-cased, you can replace '97' with '65'.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题