연습문제/C# 연습문제

6. 대소문자 변환

규남 2023. 8. 3. 18:54
반응형

<소스 코드>

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 소문자 -> 대문자
            string str1 = "abcdefg";
            string result1 = str1.ToUpper();
            Console.WriteLine(result1);

            // 아스키코드를 이용한 방법
            result1 = string.Empty;

            for(int i = 0; i < str1.Length; i++)
            {
                // 소문자 a = 97, 대문자 A = 65
                // 즉 소문자에서 대문자로 바꾸려면??
                // 97에서 32만큼 빼주면 65가 되므로 
                // 문자로 A가 만들어진다. 원리를 이해하는데
                // 도움이 되는 방법
                result1 += (char)(str1[i] - 32);
            }
            Console.WriteLine(result1);

            // 대문자 -> 소문자
            string str2 = "ABCDEFG";
            string result2 = str2.ToLower();
            Console.WriteLine(result2);

            // 아스키코드를 이용한 방법
            result2 = string.Empty;

            for (int i = 0; i < str2.Length; i++)
            {
                // 대문자 A = 65, 소문자 a = 97
                // 65에서 32만큼 더해주면 97가 되므로 
                // 문자로 a가 만들어진다. 
                result2 += (char)(str2[i] + 32);
            }
            Console.WriteLine(result2);

        }
    }
}

<결과 확인>

728x90
반응형