eg3
eg3

Reputation: 25

Is there a way to loop a char into an array?

To elaborate, what I mean is, if I wish to create an array of the alphabet:
(i.e. char[] alphabet = new char[26];)
is it possible to use a for loop, for instance, to iterate over chars as opposed to me initializing each letter individually in brackets?
(i.e. char[] alphabet = {'a','b','c',...'z'};)

Upvotes: 0

Views: 1535

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

Yes. Just add a value to a char in a loop. Like,

for (int i = 0; i < alphabet.length; i++) {
    alphabet[i] = (char) ('a' + i);
}

Alternatively, String.toCharArray() like

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

Upvotes: 1

Related Questions