C# Visual Studio/2
[C#] string.PadLeft, string.PadRight
조민상
2024. 1. 17. 09:59
PadLeft, PadRight
문자열의 정해진 길이까지 앞이나 뒤에 문자를 붙일 수 있다.
사용법 : string.PadRight( int , char )
문자열에 붙인 후 문자열의 길이(int) , 문자열에 붙일 문자(char)
아래는 사용 예제 코드이다.
using System.Collections.Generic;
namespace practice
{
class Weapon
{
public string Name { get; set; }
public int Atk { get; set; }
public Weapon(string name, int atk)
{
Name = name;
Atk = atk;
}
}
internal class Program
{
static void Main(string[] args)
{
Weapon wp = new Weapon("sword", 5);
Weapon wp2 = new Weapon("bow", 3);
Console.WriteLine("Item"+"| Atk");
Console.WriteLine($"{wp.Name}" + $"| +{wp.Atk}");
Console.WriteLine($"{wp2.Name}" + $"| +{wp2.Atk}");
Console.WriteLine();
Console.WriteLine("Item".PadRight(10, ' ')+"| Atk");
Console.WriteLine($"{wp.Name}".PadRight(10, ' ') + $"| +{wp.Atk}");
Console.WriteLine($"{wp2.Name}".PadRight(10, ' ') + $"| +{wp2.Atk}");
}
}
}
문자열의 길이가 10이 될때까지 ' '(공백)을 붙여서 깔끔하게 표시되도록 만들었다.