C# WPF 개발 메모장
[C#] 핸드폰 번호에 하이픈(Hyphen / - ) 넣기
IT김군
2018. 3. 21. 15:56
안녕하세요. IT 김군입니다.
핸드폰 번호를 하이픈 없이 입력 받아 하이픈을 넣어서 사용하여야 할 때 하이픈 넣는 방법에 대해 알아보도록 하겠습니다.
많은 방법이 있지만 저는 제일 쉽게 접할 수 있는 Substring으로 쪼개서 "-"를 중간중간 더하는 방식으로 진행하였습니다.
0111234567과 같은 10자리 번호와 01012345678과 같은 11자리 번호에 대해서 처리하였습니다.
저는 정규식으로 전화번호가 맞는지 먼저 체크하고 이 코드를 타기 때문에 가볍게 10인지 아닌지만 구분했지만
if / else 문의 조건을 조금만 수정하면 더욱 더 완벽하게 처리하실 수 있으실거에요.
해당 소스는 아래와 같습니다.
public void phoneNumHyphen(){
string phone = "0110000000";
string str_phoneNumHyphen;
string[] phoneNumSplit = new string[3];
if (phone.Length == 10)
{
phoneNumSplit[0] = phone.Substring(0, 3);
phoneNumSplit[1] = phone.Substring(3, 3);
phoneNumSplit[2] = phone.Substring(6, 4);
}
else
{
phoneNumSplit[0] = phone.Substring(0, 3);
phoneNumSplit[1] = phone.Substring(3, 4);
phoneNumSplit[2] = phone.Substring(7, 4);
}
str_phoneNumHyphen = phoneNumSplit[0] + "-" + phoneNumSplit[1] + "-" + phoneNumSplit[2];
MessageBox.Show("@@ PhoneNum : " + str_phoneNumHyphen);
}
위 소스로 빌드하면 아래와 같은 결과를 얻을 수 있습니다.
추가!!!!!!!!
더 간단한 방법이 있었습니다.
private void phoneNumHyphen()
{
string phoneNum= "01012341234";
string phoneNumHyphen;
if (phoneNum.Length == 11)
{
phoneNumHyphen = phoneNum.Insert(3, "-");
phoneNumHyphen = phoneNumHyphen.Insert(8, "-");
}
else
{
phoneNumHyphen = phoneNum.Insert(3, "-");
phoneNumHyphen = phoneNumHyphen.Insert(7, "-");
}
MessageBox.Show("@@ PhoneNum : " + phoneNumHyphen);
}
잘못된 부분이나 궁금하신 점 댓글주세요.
도움이 되셨다면 공감 한 번씩만 부탁드리겠습니다.
감사합니다.