Reputation: 59
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
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
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
Reputation: 47068
var str = "A";
char firstChar = str[0];
char nextChar = (char)((int)firstChar + 1);
var newStr = nextChar.ToString();
Upvotes: 2