programing tip

C #에서 문자열을 전화 번호로 형식화하는 방법

itbloger 2020. 6. 9. 08:18
반응형

C #에서 문자열을 전화 번호로 형식화하는 방법


"1112224444"라는 문자열이 있는데 전화 번호입니다. 파일에 저장하기 전에 111-222-4444로 형식을 지정하려고합니다. 데이터 레코드에 있으며 새 것을 할당하지 않고도이 작업을 수행 할 수 있습니다. 변하기 쉬운.

나는 생각하고 있었다 :

String.Format("{0:###-###-####}", i["MyPhone"].ToString() );

그러나 그것은 트릭을하지 않는 것 같습니다.

** 업데이트 **

확인. 이 솔루션과 함께 갔다

Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")

이제 확장명이 4 자리 미만이면 엉망이됩니다. 오른쪽에서 숫자를 채 웁니다. 그래서

1112224444 333  becomes

11-221-244 3334

어떤 아이디어?


이 답변은 숫자 데이터 유형 (int, long)에서 작동합니다. 문자열로 시작하는 경우 먼저 숫자로 변환해야합니다. 또한 초기 문자열 길이가 10 자 이상인지 확인해야합니다.

예제로 가득 찬 좋은 페이지 에서 :

String.Format("{0:(###) ###-####}", 8005551212);

    This will output "(800) 555-1212".

정규식이 더 잘 작동 할 수 있지만 이전 프로그래밍 인용문을 명심하십시오.

어떤 사람들은 문제에 직면했을 때“정규 표현을 사용할 것입니다.”라고 생각합니다. 이제 두 가지 문제가 있습니다.
comp.lang.emacs의 --Jamie Zawinski


정규식을 선호합니다.

Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");

하위 문자열로 분리해야합니다. 추가 변수없이 그렇게 있지만 특히 좋지는 않습니다. 하나의 가능한 해결책은 다음과 같습니다.

string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);

내가 아는 한 string.Format 으로이 작업을 수행 할 수는 없습니다.이를 직접 처리해야합니다. 숫자가 아닌 문자를 모두 제거한 다음 다음과 같이 할 수 있습니다.

string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));

데이터가 올바르게 입력되었다고 가정하고 정규식을 사용하여 유효성을 검사 할 수 있습니다.


나는 이것을 미국 번호에 대한 깨끗한 해결책으로 제안합니다.

public static string PhoneNumber(string value)
{ 
    value = new System.Text.RegularExpressions.Regex(@"\D")
        .Replace(value, string.Empty);
    value = value.TrimStart('1');
    if (value.Length == 7)
        return Convert.ToInt64(value).ToString("###-####");
    if (value.Length == 10)
        return Convert.ToInt64(value).ToString("###-###-####");
    if (value.Length > 10)
        return Convert.ToInt64(value)
            .ToString("###-###-#### " + new String('#', (value.Length - 10)));
    return value;
}

이것은 작동해야합니다 :

String.Format("{0:(###)###-####}", Convert.ToInt64("1112224444"));

또는 귀하의 경우 :

String.Format("{0:###-###-####}", Convert.ToInt64("1112224444"));

당신이 얻을 수있는 경우 i["MyPhone"]A와 long, 당신은 사용할 수있는 long.ToString()포맷하는 방법 :

Convert.ToLong(i["MyPhone"]).ToString("###-###-####");

숫자 형식 문자열 에 대한 MSDN 페이지를 참조하십시오 .

int보다는 long을 사용하도록주의하십시오 : int가 오버 플로우 될 수 있습니다.


static string FormatPhoneNumber( string phoneNumber ) {

   if ( String.IsNullOrEmpty(phoneNumber) )
      return phoneNumber;

   Regex phoneParser = null;
   string format     = "";

   switch( phoneNumber.Length ) {

      case 5 :
         phoneParser = new Regex(@"(\d{3})(\d{2})");
         format      = "$1 $2";
       break;

      case 6 :
         phoneParser = new Regex(@"(\d{2})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 7 :
         phoneParser = new Regex(@"(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 8 :
         phoneParser = new Regex(@"(\d{4})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 9 :
         phoneParser = new Regex(@"(\d{4})(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3 $4";
       break;

      case 10 :
         phoneParser = new Regex(@"(\d{3})(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3 $4";
       break;

      case 11 :
         phoneParser = new Regex(@"(\d{4})(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3 $4";
       break;

      default:
        return phoneNumber;

   }//switch

   return phoneParser.Replace( phoneNumber, format );

}//FormatPhoneNumber

    enter code here

실시간으로 변환 할 (미국) 전화 번호를 찾고있는 경우 이 확장 프로그램을 사용하는 것이 좋습니다. 이 방법은 숫자를 거꾸로 채우지 않고 완벽하게 작동합니다. String.Format솔루션은 작업 뒤쪽에 나타납니다. 이 확장을 문자열에 적용하십시오.

public static string PhoneNumberFormatter(this string value)
{
    value = new Regex(@"\D").Replace(value, string.Empty);
    value = value.TrimStart('1');

    if (value.Length == 0)
        value = string.Empty;
    else if (value.Length < 3)
        value = string.Format("({0})", value.Substring(0, value.Length));
    else if (value.Length < 7)
        value = string.Format("({0}) {1}", value.Substring(0, 3), value.Substring(3, value.Length - 3));
    else if (value.Length < 11)
        value = string.Format("({0}) {1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
    else if (value.Length > 10)
    {
        value = value.Remove(value.Length - 1, 1);
        value = string.Format("({0}) {1}-{2}", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));
    }
    return value;
}

Function FormatPhoneNumber(ByVal myNumber As String)
    Dim mynewNumber As String
    mynewNumber = ""
    myNumber = myNumber.Replace("(", "").Replace(")", "").Replace("-", "")
    If myNumber.Length < 10 Then
        mynewNumber = myNumber
    ElseIf myNumber.Length = 10 Then
        mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
                myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3)
    ElseIf myNumber.Length > 10 Then
        mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
                myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3) & " " &
                myNumber.Substring(10)
    End If
    Return mynewNumber
End Function

당신은 또한 이것을 시도 할 수 있습니다 :

  public string GetFormattedPhoneNumber(string phone)
        {
            if (phone != null && phone.Trim().Length == 10)
                return string.Format("({0}) {1}-{2}", phone.Substring(0, 3), phone.Substring(3, 3), phone.Substring(6, 4));
                return phone;
        }

산출:

여기에 이미지 설명을 입력하십시오


지역 번호와 기본 번호 블록 (예 : 공백, 대시, 마침표 등) 사이에 모든 종류의 구분 기호가있는 전화 번호를 입력하려고하는 상황에 처할 수 있습니다. 숫자가 아닌 모든 문자의 입력을 제거하여 작업중인 입력을 멸균 할 수 있습니다. 가장 쉬운 방법은 RegEx 표현식을 사용하는 것입니다.

string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@"\D")
    .Replace(originalPhoneNumber, string.Empty);

그런 다음 나열된 답변이 대부분의 경우 효과가 있습니다.

내선 번호 문제에 대한 답변을 얻으려면 예상되는 길이가 10보다 긴 것을 (일반 전화 번호의 경우) 벗기고 다음을 사용하여 끝에 추가하십시오.

formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)
     .ToString("###-###-#### " + new String('#', (value.Length - 10)));

이 작업을 수행하기 전에 입력 길이가 10보다 큰지 확인하려면 'if'검사를 수행하고 싶지 않은 경우 다음을 사용하십시오.

formattedPhoneNumber = Convert.ToInt64(value).ToString("###-###-####");

이 시도

string result;
if ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )
    result = string.Format("{0:(###)###-"+new string('#',phoneNumber.Length-6)+"}",
    Convert.ToInt64(phoneNumber)
    );
else
    result = phoneNumber;
return result;

건배.


정규식에서 일치를 사용하여 분할 한 다음 일치하는 형식의 문자열을 출력하십시오.

Regex regex = new Regex(@"(?<first3chr>\d{3})(?<next3chr>\d{3})(?<next4chr>\d{4})");
Match match = regex.Match(phone);
if (match.Success) return "(" + match.Groups["first3chr"].ToString() + ")" + " " + 
  match.Groups["next3chr"].ToString() + "-" + match.Groups["next4chr"].ToString();

다음은 정규 표현식을 사용하지 않고 작동합니다.

string primaryContactNumber = !string.IsNullOrEmpty(formData.Profile.Phone) ? String.Format("{0:###-###-####}", long.Parse(formData.Profile.Phone)) : "";

long.Parse를 사용하지 않으면 string.format이 작동하지 않습니다.


public string phoneformat(string phnumber)
{
String phone=phnumber;
string countrycode = phone.Substring(0, 3); 
string Areacode = phone.Substring(3, 3); 
string number = phone.Substring(6,phone.Length); 

phnumber="("+countrycode+")" +Areacode+"-" +number ;

return phnumber;
}

출력은 : 001-568-895623입니다.


C # http://www.beansoftware.com/NET-Tutorials/format-string-phone-number.aspx에 다음 링크를 사용 하십시오.

형식을 만드는 가장 쉬운 방법은 Regex를 사용하는 것입니다.

private string FormatPhoneNumber(string phoneNum)
{
  string phoneFormat = "(###) ###-#### x####";

  Regex regexObj = new Regex(@"[^\d]");
  phoneNum = regexObj.Replace(phoneNum, "");
  if (phoneNum.Length > 0)
  {
    phoneNum = Convert.ToInt64(phoneNum).ToString(phoneFormat);
  }
  return phoneNum;
}

phoneNum을 문자열 2021231234로 최대 15 자까지 전달하십시오.

FormatPhoneNumber(string phoneNum)

또 다른 방법은 하위 문자열을 사용하는 것입니다

private string PhoneFormat(string phoneNum)
    {
      int max = 15, min = 10;
      string areaCode = phoneNum.Substring(0, 3);
      string mid = phoneNum.Substring(3, 3);
      string lastFour = phoneNum.Substring(6, 4);
      string extension = phoneNum.Substring(10, phoneNum.Length - min);
      if (phoneNum.Length == min)
      {
        return $"({areaCode}) {mid}-{lastFour}";
      }
      else if (phoneNum.Length > min && phoneNum.Length <= max)
      {
        return $"({areaCode}) {mid}-{lastFour} x{extension}";
      }
      return phoneNum;
    }

확장 문제를 해결하려면 다음을 수행하십시오.

string formatString = "###-###-#### ####";
returnValue = Convert.ToInt64(phoneNumber)
                     .ToString(formatString.Substring(0,phoneNumber.Length+3))
                     .Trim();

오래된 질문을 부활 시키지는 않지만 설정이 조금 더 복잡하다면 적어도 사용하기 쉬운 방법을 제공 할 수 있다고 생각했습니다.

따라서 새로운 사용자 정의 포맷터를 만들면 string.Format전화 번호를 A로 변환하지 않고도 보다 간단한 형식을 사용할 수 있습니다long

먼저 사용자 정의 포맷터를 만들어 보겠습니다.

using System;
using System.Globalization;
using System.Text;

namespace System
{
    /// <summary>
    ///     A formatter that will apply a format to a string of numeric values.
    /// </summary>
    /// <example>
    ///     The following example converts a string of numbers and inserts dashes between them.
    ///     <code>
    /// public class Example
    /// {
    ///      public static void Main()
    ///      {          
    ///          string stringValue = "123456789";
    ///  
    ///          Console.WriteLine(String.Format(new NumericStringFormatter(),
    ///                                          "{0} (formatted: {0:###-##-####})",stringValue));
    ///      }
    ///  }
    ///  //  The example displays the following output:
    ///  //      123456789 (formatted: 123-45-6789)
    ///  </code>
    /// </example>
    public class NumericStringFormatter : IFormatProvider, ICustomFormatter
    {
        /// <summary>
        ///     Converts the value of a specified object to an equivalent string representation using specified format and
        ///     culture-specific formatting information.
        /// </summary>
        /// <param name="format">A format string containing formatting specifications.</param>
        /// <param name="arg">An object to format.</param>
        /// <param name="formatProvider">An object that supplies format information about the current instance.</param>
        /// <returns>
        ///     The string representation of the value of <paramref name="arg" />, formatted as specified by
        ///     <paramref name="format" /> and <paramref name="formatProvider" />.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            var strArg = arg as string;

            //  If the arg is not a string then determine if it can be handled by another formatter
            if (strArg == null)
            {
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(string.Format("The format of '{0}' is invalid.", format), e);
                }
            }

            // If the format is not set then determine if it can be handled by another formatter
            if (string.IsNullOrEmpty(format))
            {
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(string.Format("The format of '{0}' is invalid.", format), e);
                }
            }
            var sb = new StringBuilder();
            var i = 0;

            foreach (var c in format)
            {
                if (c == '#')
                {
                    if (i < strArg.Length)
                    {
                        sb.Append(strArg[i]);
                    }
                    i++;
                }
                else
                {
                    sb.Append(c);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        ///     Returns an object that provides formatting services for the specified type.
        /// </summary>
        /// <param name="formatType">An object that specifies the type of format object to return.</param>
        /// <returns>
        ///     An instance of the object specified by <paramref name="formatType" />, if the
        ///     <see cref="T:System.IFormatProvider" /> implementation can supply that type of object; otherwise, null.
        /// </returns>
        public object GetFormat(Type formatType)
        {
            // Determine whether custom formatting object is requested. 
            return formatType == typeof(ICustomFormatter) ? this : null;
        }

        private string HandleOtherFormats(string format, object arg)
        {
            if (arg is IFormattable)
                return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
            else if (arg != null)
                return arg.ToString();
            else
                return string.Empty;
        }
    }
}

따라서 이것을 사용하려면 다음과 같이하십시오.

String.Format(new NumericStringFormatter(),"{0:###-###-####}", i["MyPhone"].ToString());

Some other things to think about:

Right now if you specified a longer formatter than you did a string to format it will just ignore the additional # signs. For example this String.Format(new NumericStringFormatter(),"{0:###-###-####}", "12345"); would result in 123-45- so you might want to have it take some kind of possible filler character in the constructor.

Also I didn't provide a way to escape a # sign so if you wanted to include that in your output string you wouldn't be able to the way it is right now.

The reason I prefer this method over Regex is I often have requirements to allow users to specify the format themselves and it is considerably easier for me to explain how to use this format than trying to teach a user regex.

또한 클래스 이름은 문자열을 동일한 순서로 유지하고 그 안에 문자를 삽입하려는 한 실제로 문자열을 형식화하기 때문에 약간의 오해입니다.


대상 번호가 0으로 시작하면 {0 : (000) 000-####}을 시도 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/188510/how-to-format-a-string-as-a-telephone-number-in-c-sharp

반응형