0

I'm creating a class to assist in creating excel files (second question). I have a member function that creates a cell at a specific row and column location and saves it to an array.

ExcelSheet::SetValue(int row, int column, std::string szValue) {
    myWorksheet[row][column] = szValue;
}

But I'm overloading that function with the option of specifying the column as a letter/number combination, as in Excel. I want to be able to convert inputs like "A3" to Row 3 Column 1, or AB19 to Row 19 Column 28. I.E.,

ExcelSheet::SetValue(std::string szCell, std::string value) {
    // search for the alphabetical part of szCell using regex and
    // convert it to a column number
    myWorksheet[row][column] = szValue;
}

The Excel column pattern goes like this:

A, B, C, D, E... Z (1-26)  
AA, AB, AC, AD, AE... AZ (27-52)  
BA, BB, BC, BD, BE... BZ (53-78)  
...  
ZA, ZB, ZC... ZZ  
AAA, AAB, AAC... AAZ  
ABA, ABB, ABC... ABZ  
...  
AZA, AZB, AZC... AZZ  
BAA, BAB, BAC... BAZ  
...  

So I'm thinking some sort of 26-based loop would do the trick, but I'm not even sure where to start when it comes to implementing it.

Update:

My almost-working code: It compiles, but does not get the row correctly for some unclear reason.

#include <vector>
#include <string>
#include <iostream>
#include <regex>


class VectorClass {
    std::vector<std::string> vectorString;
public:
    void PrintVector(std::string szValue) {
        std::string str = "space";
        vectorString.push_back(szValue);
        vectorString.push_back(str);
        std::cout << "Loop:" << std::endl;
        for(int i=0; i < vectorString.size(); i++) {
            std::cout << vectorString[i] << std::endl;
        }
    }
    int GetColumn(std::string szValue) {
        std::regex rgx("^([a-zA-Z]+)");
        std::smatch result;
        if( regex_search(szValue, result, rgx) ) {
            std::string szResult = result[0];
            int numletters = szResult.length();
            const char * colstr = szResult.c_str();
            //char colstr[5];
            //int numofletters = 0;
            //for(int n=0;n<szResult.length();n++) {
            //  colstr[n] = szResult.substr(n,1);
            //  numofletters++;
            //}
            //char colstr[]="AEF";
            int col=0;
            for(int i=0; i<numletters; i++) {
                col = 26*col + colstr[i] - 'A' + 1;
            }
            return col;
            //return atoi(szResult.c_str());
        }
        else
            return -1;
    }
    int GetRow(std::string szValue)  {
        std::regex rgx("^[a-zA-Z]+(\d+)$");
        std::smatch result;
        if( regex_search(szValue, result, rgx) ) {
            std::cout << "test: " << result.size() << std::endl;
            for(size_t i=0; i<result.size(); ++i) {
                std::cout << result[i] << std::endl;
            }
            std::string szResult = result[0];
            return atoi(szResult.c_str());
        }
        else
            return -1;
    }
};

int main () {
    VectorClass myclass;
    //myclass.PrintVector("ship");
    std::cout << "A1 = Column " << myclass.GetColumn("A1") << ", Row " << myclass.GetRow("A1") << std::endl;
    std::cout << "B32 = Column " << myclass.GetColumn("B32") << ", Row " << myclass.GetRow("B32") << std::endl;
    std::cout << "Z65 = Column " << myclass.GetColumn("Z65") << ", Row " << myclass.GetRow("Z65") << std::endl;
    std::cout << "AA12 = Column " << myclass.GetColumn("AA12") << ", Row " << myclass.GetRow("AA12") << std::endl;
    std::cout << "AB366 = Column " << myclass.GetColumn("AB366") << ", Row " << myclass.GetRow("AB366") << std::endl;
    std::cout << "FAB43 = Column " << myclass.GetColumn("ZAB43") << ", Row " << myclass.GetRow("ZAB43") << std::endl;
    std::cout << "ZZZ43456 = Column " << myclass.GetColumn("XDE43456") << ", Row " << myclass.GetRow("XDE43456") << std::endl;
    std::cin.get();
    return 0;
}
Community
  • 1
  • 1
IDontWorkAtNASA
  • 193
  • 2
  • 16

2 Answers2

4

Note that a character has an ASCII value and you can get the column from the following:

char colstr[]="AEF";
int ii, col=0;
for(ii=0; ii<3; ii++) {
    col = 26*col + colstr[ii] - 'A' + 1;
}

A few things to note: - I use char[] - a character array - for storing the string. This makes accessing the ASCII value trivial. - I hard wired the loop to 3 - if your column labels are different lengths you might want to address that - the value 'A' in single quotes is the character "A" and thus the ASCII value 65.

EDIT: since you seemed to have trouble getting the row value, here is a very simple (C) function that will get you both - together with some code showing a few examples. I couldn't get your code to compile - apparently I don't have the library on my machine.... I am assuming that the label passed to the function is well formed: only letters followed by only numbers. It does handle lowercase letters with the toupper() function (note - this is something your code didn't do...). I figure out where the last letter is, then operate on the two parts. I return the values for row and column in the locations pointed to by row and col parameters.

#include <stdio.h>
#include <stdlib.h>

void rc(char * cellAddr, int *row, int *col) {
  int ii=0, jj, colVal=0;
  while(cellAddr[ii++] >= 'A') {};
  ii--;
  // ii now points to first character of row address
  for(jj=0;jj<ii;jj++) colVal = 26*colVal + toupper(cellAddr[jj]) -'A' + 1;
  *col = colVal;
  *row = atoi(cellAddr+ii);
}

int main() {
    int row, col;
    char cellAddr1[] = "A123";
    char cellAddr2[] = "aB321";
    char cellAddr3[] = "ABCA6543";
    rc(cellAddr1, &row, &col);
    printf("for %s the row is %d and the column is %d\n", cellAddr1, row, col);
    rc(cellAddr2, &row, &col);
    printf("for %s the row is %d and the column is %d\n", cellAddr2, row, col);
    rc(cellAddr3, &row, &col);
    printf("for %s the row is %d and the column is %d\n", cellAddr3, row, col);
}

The output this gives me is:

for A123 the row is 123 and the column is 1
for aB321 the row is 321 and the column is 28
for ABCA6543 the row is 6543 and the column is 19007
Floris
  • 45,857
  • 6
  • 70
  • 122
  • Basically work backwards through the string, summing each letter's [ASCII value-64] * [26 ^ [position-1]] (where position is right-left position) – Tim Williams Mar 06 '13 at 23:55
  • How do you get the ASCII value? – IDontWorkAtNASA Mar 07 '13 at 00:48
  • In C++ ? No idea, but I'm certian a couple of minutes of Googling would answer that. – Tim Williams Mar 07 '13 at 01:29
  • When you assign to a `char`, that is a single byte whose numerical value is the ASCII code. – Floris Mar 07 '13 at 01:41
  • Thanks. I was able to get your code to work, but for some reason I'm having a hard time doing what I thought would be simple: getting the row. Added my code to my question. – IDontWorkAtNASA Mar 08 '13 at 00:38
  • That is perhaps one possible interpretation of what I'm saying. What I'm really saying is, "You are clearly a genius, who should be working at NASA, and since it was so easy for you to solve the more difficult problem of the two almost identical problems I have, maybe you could take a glance at my short, compile-ready code and you'll probably notice in 10 seconds or less of your time the flaw that — when fixed, would make it work — rather than having me blindly search for hours on the internet". You are, of course, under no obligation to do so, but I thought it couldn't hurt to try. :) – IDontWorkAtNASA Mar 08 '13 at 20:05
  • Will do when I have a second. Flattery gets you there every time! – Floris Mar 08 '13 at 20:34
  • Thanks a lot! You sir have done a great service for your country. :) – IDontWorkAtNASA Mar 08 '13 at 22:28
  • You're welcome. I just noticed [this](http://stackoverflow.com/questions/667802/what-is-the-algorithm-to-convert-an-excel-column-letter-into-its-number?rq=1). Apparently my solution wasn't original (although it was for me...) – Floris Mar 08 '13 at 22:40
1

in Java, just in case someone wants a java version

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
    rowColFromA1("C5");
    rowColFromA1("$AB123456789");
    rowColFromA1("$C$5");
    rowColFromA1("C$5");
    rowColFromA1("$C5");
    rowColFromA1("$D5");
    rowColFromA1("$aC$5");
    rowColFromA1("$c$5");
    rowColFromA1("cBa$99");
    rowColFromA1("cBa$");
    rowColFromA1("99");
    rowColFromA1("$K$34");
}

public static int[] rowColFromA1(String a1ref) {
      int ii=0, jj, colVal=0;
      char[] cellAddr = a1ref.toCharArray();
      int[] rowCol = new int[2];
      int endOfCol;

      try {       
        while(cellAddr[ii] >= 'A' || cellAddr[ii] == '$' ) { ii++;};
        endOfCol = (cellAddr[ii-1] == '$') ? ii-1 : ii;
      } catch (ArrayIndexOutOfBoundsException aiobe) 
      { rowCol[0] = 1; rowCol[1] = 1; return rowCol;} 
      // skip $ of col, if any
      jj = (cellAddr[0] == '$') ? 1 : 0;


      // ii now points to first character of row address
      for(;jj<endOfCol;jj++) colVal = 26*colVal + Character.toUpperCase(cellAddr[jj]) -'A' + 1;
      rowCol[1] = (colVal > 0) ? colVal : 1;

      int rowVal = 0;
      for (;ii < cellAddr.length; ii++)
        rowVal = rowVal * 10 + cellAddr[ii] - '0';

      rowCol[0] = (rowVal > 0) ? rowVal : 1;
      System.out.println("R"+ rowCol[0]+"C"+rowCol[1]);

      return rowCol;
    }

}

Online java ide: http://ideone.com/69ISK8

eddyparkinson
  • 3,680
  • 4
  • 26
  • 52