C# .Net
A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 알파벳 이름 자동 생성 in C# (Excel 방식) 예제
doublesweet
2022. 9. 14. 18:05
A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 엑셀에서 사용되는 컬럼명칭과 같이 자동생성되는 코드
알파벳이므로 문자열을 26진법으로 보고 10진법으로 변환하였다가 + 1 증가하고 다시 26진법으로 변환하는 방법도 생각해봤으나 복잡할 것 같아서
간단하게 그냥 자리수별로 맨뒤자리를 증가시키고 올림이 있는경우 하나씩 올려주는거로 반복문을 만듬
예제프로그램
private string IncreaseCharactor(string input)
{
string newName = "";
int maxValue = System.Convert.ToInt32('Z');
char[] chars = input.ToCharArray();
chars[chars.Length - 1] = System.Convert.ToChar(System.Convert.ToInt32(chars[chars.Length - 1]) + 1);
foreach (char c in chars)
{
int unicode = System.Convert.ToInt32(c);
}
for (int i = chars.Count() - 1; i >= 0; i--)
{
// Z를 넘어간 경우
if (System.Convert.ToInt32(chars[i]) > maxValue)
{
// 차이 계산 (1씩 증가하면 1임)
int gap = System.Convert.ToInt32(chars[i]) - maxValue;
// A부터 더해진 만큼 증가
chars[i] = System.Convert.ToChar(System.Convert.ToInt32('A') + gap - 1);
// 앞자리가 있으면 앞자리 수 증가
if (i > 0)
{
chars[i - 1] = System.Convert.ToChar(System.Convert.ToInt32(chars[i - 1]) + 1);
}
// 맨 앞자리인 경우는 맨 앞에 A 추가
else
{
newName = new string(chars);
newName = newName.Insert(0, "A");
return newName;
}
}
}
newName = new string(chars);
return newName;
}