0

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'};)

0

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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.
@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).
@ElliottFrisch - I fixed my code and even upvoted your code. Could you please remove my downvote?
Or for (char c = 'a'; c <= 'z'; c++).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.