Chip
Chip

Reputation: 155

Java loop through all letters of the alphabet plus '

I want to creat a loop that goes through all the alphabet from a to z, but then after z, I want it to try the apostrophe '. Can I do that all in one loop? What I have now:

  for(char ch = 'a' ; ch <= 'z' ; ++ch ){
      //do something with ch
 } 

for example, let's say I want to take the word "Hi" and turn it into: Hia, Hib, Hic, Hid, ... Hix, Hiy, Hiz, Hi'

Can this be done?

Upvotes: 0

Views: 2791

Answers (2)

Pinaki Mukherjee
Pinaki Mukherjee

Reputation: 1656

The above answer is correct. But the character array missing character 'n' which took me some time to debug. I am posting this as answer as I could not edit the above one. If you are copy pasting please take the below array:

String chars = "abcdefghijklmnopqrstuvwxyz";
for (char ch : chars.toCharArray()) {
    System.out.printf("Hi%c%n", ch);
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

Yes, it can be done. One solution: iterate from 0 to 27 (exclusive). For every i less than 26 use 'a' + i when you get to 26 change the value to a '. Like,

for (int i = 0; i < 27; i++) {
    char ch = (char) ('a' + i);
    if (i == 26) {
        ch = '\'';
    }
    System.out.printf("Hi%c%n", ch);
}

Another way you could do it, build a String of suffix characters and iterate that. Like,

String chars = "abcdefghijklmopqrstuvwxyz'";
for (char ch : chars.toCharArray()) {
    System.out.printf("Hi%c%n", ch);
}

Upvotes: 2

Related Questions