作为一种选择,您可以创建一个由两个字符组成的新数据类型(类似于std::pair<char,char>
并为此定义算术。
但是,我认为继续使用int
(or unsigned int
) 进行计数和算术会更简单,并定义一个to_col_heading
将整数转换为 Excel 的一/二字符列标题的函数:
#include <string>
#include <iostream>
#include <stdexcept>
#include <iterator>
/* This is the function that performs
the transformation. */
std::string to_col_heading(unsigned i)
{
if (i > 26+26*26)
throw std::overflow_error
("Value too large for transformation into Excel column heading.");
char char1 = 'A' + (i / 26) - 1;
char char2 = 'A' + (i % 26);
if (char1 < 'A')
return std::string(&char2,&char2 + 1);
else
return std::string(&char1,&char1 + 1) + char2;
}
int main()
{
std::ostream_iterator<std::string> out(std::cout,", ");
for (unsigned i = 0 ; i < 26+26*26 ; i += 5)
*out = to_col_heading(i);
std::cout << std::endl;
return 0;
}
输出:
A, F, K, P, U, Z, AE, AJ, AO, AT, AY, BD, BI, BN, BS, BX, CC, CH, CM, CR, CW, DB, DG, DL, DQ, DV, EA, EF, EK, EP, EU, EZ, FE, FJ, FO, FT, FY, GD, GI, GN, GS, GX, HC, HH, HM, HR, HW, IB, IG, IL, IQ, IV, JA, JF, JK, JP, JU, JZ, KE, KJ, KO, KT, KY, LD, LI, LN, LS, LX, MC, MH, MM, MR, MW, NB, NG, NL, NQ, NV, OA, OF, OK, OP, OU, OZ, PE, PJ, PO, PT, PY, QD, QI, QN, QS, QX, RC, RH, RM, RR, RW, SB, SG, SL, SQ, SV, TA, TF, TK, TP, TU, TZ, UE, UJ, UO, UT, UY, VD, VI, VN, VS, VX, WC, WH, WM, WR, WW, XB, XG, XL, XQ, XV, YA, YF, YK, YP, YU, YZ, ZE, ZJ, ZO, ZT, ZY,
为了支持最多 3 个(字母)数字的列标题,下面的函数起作用。它完全分别处理前 26 个值,以简化其余值的计算。我还介绍了一些静态常量,以更一致的方式处理 26 的幂。对于三位数,您需要 26 0、26 1和 26 2,但系统可以扩展为涵盖任意位数。
我确信有办法优化它以提高速度;这不是这里的重点。
std::string to_col_heading(unsigned i)
{
const static unsigned pow1 = 26;
const static unsigned pow2 = 26*26;
const static unsigned max = pow1 + pow2 + 26 * pow2;
if (i < pow1)
{
char c = 'A' + i % pow1;
return std::string(&c,&c+1);
}
if (i > max)
throw std::overflow_error
("Value too large for transformation into Excel column heading.");
i -= pow1;
char char1 = 'A' + (i / pow2) - 1;
char char2 = 'A' + (i%pow2) / pow1;
char char3 = 'A' + i % pow1;
if (char1 < 'A')
return std::string(&char2,&char2 + 1) + char3;
else
return std::string(&char1,&char1 + 1) + char2 + char3;
}