Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# change string value to be next value in alphabetical order

Tags:

c#

So this is what i'm trying to do. I have a string alphaCode, and what i simply want to do is increase from letter A to letter B. I did a way that assigned each letter an int and then did int++, but i'm assuming there has to be a better way.

string alphaCode = "a"

result = "b"

2 Answers

string GetNextCode(string alphaCode)
{
    Debug.Assert(alphaCode.Length == 1 && Regex.IsMatch(alphaCode, "[a-yA-y]"));

    var next = (char) (alphaCode[0] + 1);
    return next.ToString();
}

Assert is there just to communicate intentions - i.e. that I did understand your requirements right. It is even somewhat redundant.

like image 132
Ivan Danilov Avatar answered Dec 10 '25 16:12

Ivan Danilov


If you use a char type you can do it like this:

char alphaChar = 'a';
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
Console.WriteLine(alphaChar++);
like image 38
Franchesca Avatar answered Dec 10 '25 15:12

Franchesca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!