Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment of Alphabet in c#

Tags:

I am exporting my data into Excel Using Open XML. now i want to increment of alphabet like as columns 'A1' to 'B1',...'Z1', 'AA1'.

I have assign 'A1' into variable and i want to increment alphabet to 'B1'.

Please provide any method/code through that can increment alphabet 'A1' to 'B1'..'Z1','AA1'.

like image 207
Pankaj Agarwal Avatar asked Jun 23 '11 12:06

Pankaj Agarwal


People also ask

Can you increment 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 .

What does char ++ do in c?

Software Engineering C C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.

Can we increment string in c?

When you increment a pointer, it points to the next object. Since these are pointers to characters, incrementing them makes them point to the next character. Your foobar function just throws away the incremented values though. It doesn't return them.


2 Answers

This can be done:

char c1 = 'A';
c1++; // c1 is 'B' now

and you can add the numbering as a string, even the concatenated characters can be generated the same way:

pseudo code:

If Reached_Z Then Add_Another_A
like image 61
Ken D Avatar answered Oct 27 '22 07:10

Ken D


This example uses an iterator capable of going from A through ZZ.

public static IEnumerable<string> GetColumns()
{
   string s = null;
   for (char c2 = 'A'; c2 <= 'Z' + 1; c2++)
   {
      for (char c = 'A'; c <= 'Z'; c++)
      {
         yield return s + c;
      }
      s = c2.ToString ();
   }
}

This sample starts at A1 and goes through AA1

string currentCell = "A1";
int currentRow = int.Parse(Regex.Match(currentCell, @"\d+").Value);
string currentCol = Regex.Match(currentCell, @"[A-Z]+").Value;
foreach (string column in GetColumns().Where (c => c >= currentCol && currentCol <= "AA"))
{
   Console.WriteLine (column + currentRow);
}

This sample starts at C5 and enumerates through the next 26 columns.

int columnsToAdd = 26;
currentCell = "C5";
currentRow = int.Parse(Regex.Match(currentCell, @"\d+").Value);
currentCol = Regex.Match(currentCell, @"[A-Z]+").Value;
foreach (string column in GetColumns().Where (c => c >= currentCol))
{
   if (columnsToAdd--) == 0)
      break;
   Console.WriteLine (column + currentRow);
}
like image 32
agent-j Avatar answered Oct 27 '22 07:10

agent-j