用 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

更新時間: 01-11-2019

208 次瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.