I need to code a method that increment a string value from AAA to ZZZ with cyclic rotation (next value after ZZZ is AAA)
Here is my code:
public static string IncrementValue(string value) {
if (string.IsNullOrEmpty(value) || value.Length != 3) {
string msg = string.Format("Incorrect value ('{0}' is not between AAA and ZZZ)", value);
throw new ApplicationException(msg);
}
if (value == "ZZZ") {
return "AAA";
}
char pos1 = value[0];
char pos2 = value[1];
char pos3 = value[2];
bool incrementPos2 = false;
bool incrementPos1 = false;
if (pos3 == 'Z') {
pos3 = 'A';
incrementPos2 = true;
} else {
pos3++;
}
if (incrementPos2 && pos2 == 'Z') {
pos2 = 'A';
incrementPos1 = true;
} else {
if (incrementPos2) {
if (pos2 == 'Z') {
pos2 = 'A';
incrementPos1 = true;
}
pos2++;
}
}
if (incrementPos1) {
pos1++;
}
return pos1.ToString() + pos2.ToString() + pos3.ToString();
}
I know this piece of code is quite dirty and not very efficient but I dont know how to do it properly.
How is secured this snippet?
(this will only run on windows plaform)
How can I optimize-it and make it more readable ?
Thanks for your comments
Think about it mathematically: Your strings (AAA, AAB, …) behave just like natural numbers (000, 001, …), with the exception of being base 26 instead of base 10.
So, you can use the same principle. Here is some code: