본문 바로가기

.NET/C# Basic

[C#] String.Format 을 이용한 문자정렬 왼쪽 오른쪽 가운데 | String alignment Left Right Center

반응형

기초를 튼튼히 하면 삽질을 줄일수 있어요!
You based foundation when the shoveling to reduce.


Result :




Code :

        static void Main(string[] args)
        {
            Console.WriteLine("123456789012345678901234567890123456789012");// 총길이 42칸
            Console.WriteLine(String.Format("{0,42}", "test")); //우측정렬
            Console.WriteLine(String.Format("{0,-42}", "te13123123st")); //좌측정렬
            Console.WriteLine(String.Format("{0}", "1").PadLeft(42 - (21 - ("1".Length / 2))));// 가운데정렬
            Console.WriteLine(String.Format("{0}", "123").PadLeft(42 - (21 - ("123".Length / 2))));
            Console.WriteLine(String.Format("{0}", "12345").PadLeft(42 - (21 - ("12345".Length / 2))));
            Console.WriteLine(String.Format("{0}", "1234567890").PadLeft(42 - (21 - ("1234567890".Length / 2))));
            Console.WriteLine(String.Format("{0}", "123451234567890").PadLeft(42 - 
(21 - ("123451234567890".Length / 2))));
            Console.WriteLine(String.Format("{0}", "12345678901234567890").PadLeft(42 - 
(21 - ("12345678901234567890".Length / 2))));
            Console.WriteLine("123456789012345678901234567890123456789012");
            
        }