Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementation of char

Tags:

I found some question asking how to let char 'B' to return 'C' and then 'D' etc. The answers were quite complex and mostly just overkill.

Why not to use simply this:

char X='A'; X++ 

EDIT: It goes from A to Z and what next?

like image 740
Loj Avatar asked Jan 03 '11 08:01

Loj


People also ask

Can we increment char in C?

Yes, you can apply the ++ increment operator to an object of type char , with the expected results in most cases: char c = 42; c++; printf("c = %d\n", c); // prints 43.

Why 128 is the value range of char?

128 is a value range for some kinds of character because the old ASCII character set from the 1960s had 128 characters.

What happens when you increment a char in C?

Because your compiler defaults char to signed char . So the range of values for it is -128 to 127, and incrementing 127 is triggering wraparound. If you want to avoid this, be explicit, and declare your variable as unsigned char .


1 Answers

If you just want to increment :

Char x = 'A'; Char y = (Char)(Convert.ToUInt16(x) + 1); 

But, if you want an excel like column :

    // (1 = A, 2 = B...27 = AA...703 = AAA...)     public static string GetColNameFromIndex(int columnNumber)     {         int dividend = columnNumber;         string columnName = String.Empty;         int modulo;          while (dividend > 0)         {             modulo = (dividend - 1) % 26;             columnName = Convert.ToChar(65 + modulo).ToString() + columnName;             dividend = (int)((dividend - modulo) / 26);         }          return columnName;     }      // (A = 1, B = 2...AA = 27...AAA = 703...)     public static int GetColNumberFromName(string columnName)     {         char[] characters = columnName.ToUpperInvariant().ToCharArray();         int sum = 0;         for (int i = 0; i < characters.Length; i++)         {             sum *= 26;             sum += (characters[i] - 'A' + 1);         }         return sum;     } 
like image 175
kerrubin Avatar answered Dec 10 '22 20:12

kerrubin