C++ 代码实现 Excel 坐标转换:A1 格式和 RXCY 格式
#include
std::string convertToA1(std::string coord) { int row_index = coord.find('R') + 1; int col_index = coord.find('C'); int row = std::stoi(coord.substr(row_index, col_index - row_index)); int col = std::stoi(coord.substr(col_index + 1)); std::string col_name = ""; while (col > 0) { col--; col_name = char('A' + col % 26) + col_name; col /= 26; } return col_name + std::to_string(row); }
std::string convertToRXCY(std::string coord) { int col_index = 0; while (col_index < coord.length() && !isdigit(coord[col_index])) { col_index++; } int row = std::stoi(coord.substr(col_index)); std::string col_name = coord.substr(0, col_index); int col = 0; for (char c : col_name) { col = col * 26 + (c - 'A' + 1); } return "R" + std::to_string(row) + "C" + std::to_string(col); }
int main() { int n; std::cin >> n; std::cin.ignore();
std::string* coords = new std::string[n];
for (int i = 0; i < n; i++) {
std::getline(std::cin, coords[i]);
}
for (int i = 0; i < n; i++) {
if (coords[i][0] == 'R' && isdigit(coords[i][1]) && coords[i].find('C') != std::string::npos) {
std::cout << convertToA1(coords[i]) << std::endl;
} else {
std::cout << convertToRXCY(coords[i]) << std::endl;
}
}
delete[] coords;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pE02 著作权归作者所有。请勿转载和采集!