I have a question about iterate through the Alphabet. I would like to have a loop that begins with "a" and ends with "z". After that, the loop begins "aa" and count to "az". after that begins with "ba" up to "bz" and so on...
Anybody know some solution?
Thanks
EDIT: I forgot that I give a char "a" to the function then the function must return b. if u give "bnc" then the function must return "bnd"
Edit: Made it do exactly as the OP's latest edit wants
This is the simplest solution, and tested:
First effort, with just a-z then aa-zz
Note that this will stop at 'zz'. Of course, there's some ugly duplication here in terms of the loops. Fortunately, that's easy to fix - and it can be even more flexible, too:
Second attempt: more flexible alphabet
Now if you want to generate just a, b, c, d, aa, ab, ac, ad, ba, ... you'd call
GetExcelColumns("abcd")
.Third attempt (revised further) - infinite sequence
It's possible that it would be cleaner code using recursion, but it wouldn't be as efficient.
Note that if you want to stop at a certain point, you can just use LINQ:
"Restarting" the iterator
To restart the iterator from a given point, you could indeed use
SkipWhile
as suggested by thesoftwarejedi. That's fairly inefficient, of course. If you're able to keep any state between call, you can just keep the iterator (for either solution):Alternatively, you may well be able to structure your code to use a
foreach
anyway, just breaking out on the first value you can actually use.Here's my attempt using recursion:
Then simply call
PrintAlphabet("abcd", "")
;just curious , why not just