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'};)
Add a comment
|
1 Answer
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();
4 Comments
eg3
I understand the second piece of code where the toCharArray method created a new character array from the string, but I do not understand why you casted char--or that's how I am interpreting it. Can you explain to me what is going on there or provide a resource that will help me better understand what is happening? Thanks.
Elliott Frisch
@eg3
char is an integral type in Java. char + int is an int. You want the char. In other words, 'a' + 1 is 'b' (as an int).armani
@ElliottFrisch - I fixed my code and even upvoted your code. Could you please remove my downvote?
chrylis -cautiouslyoptimistic-
Or
for (char c = 'a'; c <= 'z'; c++).