I want to have a java method that gives me the specified index, the corresponding excel letter set, for example:
258 => IZ (last index)
30 => AD
120 => DR
56 => BD
The first method gives the correct result, but it is very dumb, and I do not like it. I tried to build a second method, which involves a little thought. I have already seen methods using String Builder or something like this,
but I tried to create the method aka bestGetColumnName myself .
better 258 => IHGFEDCBAX (not normal)
better 30 => AD (OK, 2nd alphabet rounded)
better 120 => DCBAP (not normal)
better 56 => BAD (it seems that the 3rd alphabet round breaks my logic)
public String getColumnName(int index){
String[] letters = {
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R",
"S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH",
"AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV",
"AW","AX","AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ",
"BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX",
"BY","BZ","CA","CB","CC","CD","CE","CG","CH","CI","CJ","CK","CL","CM",
"CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ","DA",
"DB","DC","DD","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP",
"DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ","EA","EB","EC","ED",
"EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER",
"ES","ET","EU","EV","EW","EX","EY","EZ","FA","FB","FC","FD","FE","FF",
"FG","FH","FI","FJ","FK","FL","FM","FN","FO","FP","FQ","FR","FS","FT",
"FU","FV","FW","FX","FY","FZ","GA","GB","GC","GD","GE","GF","GG","GH",
"GI","GJ","GK","GL","GM","GN","GO","GP","GQ","GR","GS","GT","GU","GV",
"GW","GX","GY","GZ","HA","HB","HC","HD","HE","HF","HG","HH","HI","HJ",
"HK","HL","HM","HN","HO","HP","HQ","HR","HS","HT","HU","HV","HW","HX",
"HY","HZ","IA","IB","IC","ID","IE","IF","IG","IH","II","IJ","IK","IL",
"IM","IN","IO","IP","IQ","IR","IS","IT","IU","IV","IW","IX","IY","IZ"
};
if (index<=letters.length){
return letters[index-1];
}else{
return null;
}
}
, , , StringBuilder
, , char
, String
integers
, java version (1.5.x) , , , .
public String betterGetColumnName(int index){
int res=0;
String s = "";
char h='0';
while(index>26){
res=index/26;
h=(char)(res+64);
s+=h;
index -=26;
}
h=(char)(index+64);
s+=h;
return s;
}