Character increment in string

I have the following code:

string str="A"; 

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

Can anyone suggest a way to do this?

+4
source share
4 answers

Instead of whole lines, use Char .

 char aChar = 'A'; aChar++; // After this line executes, `aChar` is `B` 
+9
source
 var str = "A"; char firstChar = str[0]; char nextChar = (char)((int)firstChar + 1); var newStr = nextChar.ToString(); 
+2
source

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(); } 
+1
source

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

You can do this if your variable is a string:

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

Source: https://habr.com/ru/post/1439137/


All Articles