본문 바로가기

C# .Net

A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 알파벳 이름 자동 생성 in C# (Excel 방식) 예제

A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 엑셀에서 사용되는 컬럼명칭과 같이 자동생성되는 코드

 

알파벳이므로 문자열을 26진법으로 보고 10진법으로 변환하였다가 + 1 증가하고 다시 26진법으로 변환하는 방법도 생각해봤으나 복잡할 것 같아서

간단하게 그냥 자리수별로 맨뒤자리를 증가시키고 올림이 있는경우 하나씩 올려주는거로 반복문을 만듬

 

예제프로그램

WinFormsApp1.zip
0.19MB

        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;
        }

'C# .Net' 카테고리의 다른 글

TCP/IP 통신 Server 및 Client 예제 in C# (Winform)  (0) 2022.09.20
RESTful API Server 구현 예제 in C#  (0) 2022.09.19
Json / Xml to DataSet  (0) 2022.02.25
.Net C/C++/C# Stack Size 변경 방법  (0) 2021.11.17