Traverse the alphabet from a to z using C#
P粉982881583
2023-08-23 09:51:55
<p>I have a question about traversing the alphabet.
I want a loop that starts at "a" and ends at "z". Then, the loop starts from "aa" and counts up to "az". Then start from "ba", go to "bz", and so on...</p>
<p>Does anyone know a solution? </p>
<h2>Thank you</h2>
<p>Edit: I forgot, I give a character "a" to the function and then the function must return "b". If "bnc" is given, the function must return "bnd". </p>
First try, just use a-z then aa-zz
Note that this will stop at 'zz'. Of course, there are some ugly repetitions in the loop. Fortunately, this is easy to fix - and it can also be more flexible:
Second attempt: a more flexible alphabet
Now, if you only want to generate a, b, c, d, aa, ab, ac, ad, ba, etc., you can call
GetExcelColumns("abcd")
.Third Attempt (Further Revised) - Infinite Sequence
Maybe using recursion will lead to clearer code, but the efficiency will not be that high.
Please note that if you want to stop at a specific point, you can use LINQ:
"Restart" iterator
To restart the iterator from a given point, you can use
SkipWhile
as thesoftwarejedi suggested. Of course, this is quite inefficient. If you can maintain any state between calls, you can retain the iterator (for either solution):Alternatively, you might be able to structure your code to use
foreach
, breaking when the first value is found that can actually be used.Edit: Make it exactly as per the latest edits to the original post
This is the simplest solution and tested: