Rashmi Salokhe
Rashmi Salokhe

Reputation: 59

Increment character in string

I have the following code:

string str="A";

I want to get the next alphabetical character programmatically (so B, C, D, E etc.)

Can anyone suggest a way of doing this?

Upvotes: 5

Views: 16995

Answers (4)

Willy David Jr
Willy David Jr

Reputation: 9171

I am looking for the same thing, and I am using string so I need to cast it.

You can do this if your variable is string:

string foo = "b";
char result = Convert.ToChar(foo[0] + 1); //Will result to 'c'

Upvotes: 0

Isaac
Isaac

Reputation: 69

If you are looking for something like "A".. "Z"..."AA", "AB"..."ZZ"..."AAA"... , here is the code,

  public static string IncrementString(this string input)
    {
        string rtn = "A";
        if (!string.IsNullOrWhiteSpace(input))
        {
            bool prependNew = false;
            var sb = new StringBuilder(input.ToUpper());
            for (int i = (sb.Length - 1); i >= 0; i--)
            {
                if (i == sb.Length - 1)
                {
                    var nextChar = Convert.ToUInt16(sb[i]) + 1;
                    if (nextChar > 90)
                    {
                        sb[i] = 'A';
                        if ((i - 1) >= 0)
                        {
                            sb[i - 1] = (char)(Convert.ToUInt16(sb[i - 1]) + 1);
                        }
                        else
                        {
                            prependNew = true;
                        }
                    }
                    else
                    {
                        sb[i] = (char)(nextChar);
                        break;
                    }
                }
                else
                {
                    if (Convert.ToUInt16(sb[i]) > 90)
                    {
                        sb[i] = 'A';
                        if ((i - 1) >= 0)
                        {
                            sb[i - 1] = (char)(Convert.ToUInt16(sb[i - 1]) + 1);
                        }
                        else
                        {
                            prependNew = true;
                        }
                    }
                    else
                    {
                        break;
                    }

                }
            }
            rtn = sb.ToString();
            if (prependNew)
            {
                rtn = "A" + rtn;
            }
        }

        return rtn.ToUpper();
    }

Upvotes: 6

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47068

var str = "A";
char firstChar = str[0];
char nextChar = (char)((int)firstChar + 1);
var newStr = nextChar.ToString();

Upvotes: 2

Oded
Oded

Reputation: 499382

Instead of whole strings, use Char.

char aChar = 'A';

aChar++; // After this line executes, `aChar` is `B`

Upvotes: 10

Related Questions