82

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 to Scala's 'a' to 'z'

4

19 回答 19

211

我认为这最终会更干净一些,您不必处理减法和索引:

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
于 2013-07-10T16:21:56.947 回答
48
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'};
于 2013-07-10T16:25:11.117 回答
19

getAlphabet方法使用与该问题类似的技术来为任意语言生成字母表。

将任何语言定义为枚举,然后调用getAlphabet.

char[] armenianAlphabet = getAlphabet(LocaleLanguage.ARMENIAN);
char[] russianAlphabet = getAlphabet(LocaleLanguage.RUSSIAN);

// get uppercase alphabet 
char[] currentAlphabet = getAlphabet(true);
    
System.out.println(armenianAlphabet);
System.out.println(russianAlphabet);
System.out.println(currentAlphabet);

结果

I/System.out:աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ

I/System.out: абвгдежзийклмнопрстуфхцчшщъыьэюя

I/System.out:ABCDEFGHIJKLMNOPQRSTUVWXYZ

private char[] getAlphabet() {
    return getAlphabet(false);
}

private char[] getAlphabet(boolean flagToUpperCase) {
    Locale locale = getResources().getConfiguration().locale;
    LocaleLanguage language = LocaleLanguage.getLocalLanguage(locale);
    return getAlphabet(language, flagToUpperCase);
}

private char[] getAlphabet(LocaleLanguage localeLanguage, boolean flagToUpperCase) {
    if (localeLanguage == null)
        localeLanguage = LocaleLanguage.ENGLISH;

    char firstLetter = localeLanguage.getFirstLetter();
    char lastLetter = localeLanguage.getLastLetter();
    int alphabetSize = lastLetter - firstLetter + 1;

    char[] alphabet = new char[alphabetSize];

    for (int index = 0; index < alphabetSize; index++) {
        alphabet[index] = (char) (index + firstLetter);
    }

    if (flagToUpperCase) {
        alphabet = new String(alphabet).toUpperCase().toCharArray();
    }

    return alphabet;
}

private enum LocaleLanguage {
    ARMENIAN(new Locale("hy"), 'ա', 'ֆ'),
    RUSSIAN(new Locale("ru"), 'а','я'),
    ENGLISH(new Locale("en"), 'a','z');

    private final Locale mLocale;
    private final char mFirstLetter;
    private final char mLastLetter;

    LocaleLanguage(Locale locale, char firstLetter, char lastLetter) {
        this.mLocale = locale;
        this.mFirstLetter = firstLetter;
        this.mLastLetter = lastLetter;
    }

    public Locale getLocale() {
        return mLocale;
    }

    public char getFirstLetter() {
        return mFirstLetter;
    }

    public char getLastLetter() {
        return mLastLetter;
    }

    public String getDisplayLanguage() {
        return getLocale().getDisplayLanguage();
    }

    public String getDisplayLanguage(LocaleLanguage locale) {
        return getLocale().getDisplayLanguage(locale.getLocale());
    }

    @Nullable
    public static LocaleLanguage getLocalLanguage(Locale locale) {
        if (locale == null)
            return LocaleLanguage.ENGLISH;

        for (LocaleLanguage localeLanguage : LocaleLanguage.values()) {
            if (localeLanguage.getLocale().getLanguage().equals(locale.getLanguage()))
                return localeLanguage;
        }

        return null;
    }
}
于 2017-09-27T12:26:39.750 回答
18

这是一个有趣的 Unicode 解决方案:

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

这会生成一个小写版本的字母,如果你想要大写,你可以用 '65' 替换 '97'。

于 2015-01-01T22:00:53.390 回答
14

在带有 Stream API 的 Java 8 中,您可以执行此操作。

IntStream.rangeClosed('A', 'Z').mapToObj(var -> (char) var).forEach(System.out::println);
于 2018-08-23T09:14:31.170 回答
9

如果您使用的是 Java 8

char[] charArray = IntStream.rangeClosed('A', 'Z')
    .mapToObj(c -> "" + (char) c).collect(Collectors.joining()).toCharArray();
于 2016-07-26T09:48:37.107 回答
6
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"};
于 2017-05-02T19:02:24.200 回答
4

一旦我确定你会得到字母,请检查a这个z

for (char c = 'a'; c <= 'z'; c++) {
    al.add(c);
}
System.out.println(al);'
于 2016-02-19T05:57:30.587 回答
3

以下是基于@tom thomas回答的一些替代方案。

字符数组:

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

字符串数组:

注意:如果您的分隔符也是值之一,则无法正常工作。

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

字符串列表:

注意:如果您的分隔符也是值之一,则无法正常工作。

List<String> list = Arrays.asList(IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(","));
于 2020-01-16T19:42:33.170 回答
3

使用io.vavr

public static char[] alphanumericAlphabet() {
    return CharSeq
            .rangeClosed('0','9')
            .appendAll(CharSeq.rangeClosed('a','z'))
            .appendAll(CharSeq.rangeClosed('A','Z'))
            .toCharArray();
}
于 2018-10-06T10:47:03.310 回答
1

对于搜索 Kotlin 解决方案并在此处结束的 Android 开发人员:

// Creates List<Char>
val chars1 = ('a'..'z').toList()
// Creates Array<Char> (boxed)
val chars2 = ('a'..'z').toList().toTypedArray()
// Creates CharArray (unboxed)
val chars3 = CharArray(26) { 'a' + it }
// Creates CharArray (unboxed)
val chars4 = ('a'..'z').toArray()
fun CharRange.toArray() = CharArray(count()) { 'a' + it }

要了解我所说的“装箱”和“未装箱”的意思,请参阅这篇文章
非常感谢这个 Kotlin 讨论线程

于 2021-09-24T07:51:42.597 回答
1

简单是一种美德。使用这个自然可读的数组:

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'};
于 2020-10-03T16:53:32.887 回答
0

使用 Java 8 流

  char [] alphabets = Stream.iterate('a' , x -> (char)(x + 1))
            .limit(26)
            .map(c -> c.toString())
            .reduce("", (u , v) -> u + v).toCharArray();
于 2019-07-26T09:30:21.673 回答
0
char[] abc = new char[26];

for(int i = 0; i<26;i++) {
    abc[i] = (char)('a'+i);
}
于 2017-10-31T23:06:01.137 回答
0

要获取除小写字母之外的大写字母,您还可以执行以下操作:

String alphabetWithUpper = "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".toUpperCase();
char[] letters = alphabetWithUpper.toCharArray();
于 2020-01-31T21:36:45.750 回答
0
const alphabetArray = "abcdefghijklmnopqrstuvwxyz".split("");
于 2022-02-25T15:05:27.897 回答
-1
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));
    } 
于 2015-03-09T22:33:29.730 回答
-1

在科特林你可以做到这一点

var alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray()
于 2021-06-02T03:06:02.520 回答
-6
for (char letter = 'a'; letter <= 'z'; letter++)
{
    System.out.println(letter);
}
于 2014-10-16T09:32:11.327 回答