在C ++中从列标题中查找Excel列号

我们知道excel列号是字母的。它从A开始,在Z之后,将是AA,AB,ZZ,然后是AAA,AAB,ZZZ,依此类推。所以第1列是A,第27列是Z。在这里,我们将看到如果给出列数,则如何获取列字母。因此,如果列号为80,则它将为CB。

假设我们有一个数字n,其值为28,则需要使用26提醒。如果余数为0,则该数字为26、52,依此类推。然后我们将Z放入输出字符串中。n的值变为n / 26 –1。如果余数不为零,则只需将相应的字符插入字符串中,然后执行n = n / 26。最后,将打印字符串的反面。

示例

#include<iostream>
#include<algorithm>
using namespace std;
void showColumnLetters(int n) {
   string str = "";
   while (n) {
      int rem = n%26;
      if (rem==0) {
         str += 'Z';
         n = (n/26)-1;
      }
      else{
         str += (rem-1) + 'A';
         n = n/26;
      }
   }
   reverse(str.begin(), str.begin() + str.length());
   cout << str << endl;
}
int main() {
   int n = 700;
   cout << "Cell name of " << n << " is: ";
   showColumnLetters(700);
}

输出结果

Cell name of 700 is: ZX