web-dev-qa-db-fra.com

Comment formater une chaîne en tant que numéro de téléphone en C #

J'ai une chaîne "1112224444" c'est un numéro de téléphone. Je souhaite formater le 111-222-4444 avant de le stocker dans un fichier. Il se trouve sur un enregistrement de données et je préférerais pouvoir le faire sans en affecter un nouveau. variable.

Je pensais:

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

mais cela ne semble pas faire l'affaire.

** MISE À JOUR **

D'accord. Je suis allé avec cette solution

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

Maintenant, il est perturbé lorsque l’extension a moins de 4 chiffres. Il va remplir les chiffres de la droite. alors

1112224444 333  becomes

11-221-244 3334

Des idées?

149
Brian G

Veuillez noter que cette réponse fonctionne avec les types de données numériques (int, long). Si vous commencez avec une chaîne, vous devrez d'abord la convertir en nombre. En outre, veuillez prendre en compte le fait que vous devez valider que la chaîne initiale compte au moins 10 caractères.

D'un bonne page plein d'exemples:

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

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

Bien qu'une expression régulière puisse fonctionner encore mieux, gardez à l'esprit l'ancienne citation de programmation:

Certaines personnes, confrontées à un problème, se disent "Je sais, je vais utiliser des expressions régulières". Maintenant, elles ont deux problèmes.
- Jamie Zawinski, dans comp.lang.emacs

188
Sean

Je préfère utiliser des expressions régulières:

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

Vous devrez le diviser en sous-chaînes. Bien que vous puissiez le faire sans variables supplémentaires, cela ne serait pas particulièrement agréable. Voici une solution potentielle:

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);
42
Jon Skeet

Je suggère cela comme une solution propre pour les numéros américains.

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;
}
21
Jerry Nixon - MSFT

Autant que je sache, vous ne pouvez pas faire cela avec string.Format ... vous devrez gérer cela vous-même. Vous pouvez simplement supprimer tous les caractères non numériques et ensuite faire quelque chose comme:

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

Cela suppose que les données ont été entrées correctement, ce que vous pouvez utiliser des expressions régulières pour valider.

21
mattruma

Cela devrait fonctionner:

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

OU dans votre cas:

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

Si vous pouvez obtenir i["MyPhone"] en tant que long, vous pouvez utiliser la méthode long.ToString() pour le formater:

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

Voir la page MSDN sur Chaînes de format numérique .

Veillez à utiliser long plutôt qu'int: int pourrait déborder.

14
Joel Coehoorn

Si vous cherchez un numéro de téléphone (américain) à convertir en temps réel. Je suggère d'utiliser cette extension. Cette méthode fonctionne parfaitement sans indiquer les chiffres à l'envers. La solution String.Format semble fonctionner en arrière. Appliquez simplement cette extension à votre chaîne.

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;
}
5
James Copeland
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
5
underscore

Vous pouvez aussi essayer ceci:

  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;
        }

Sortie:

enter image description here

3
atik sarker
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
3
Arin

Vous pouvez vous retrouver dans la situation où vous avez des utilisateurs qui tentent de saisir des numéros de téléphone avec toutes sortes de séparateurs entre l'indicatif régional et le bloc de numéros principal (par exemple, des espaces, des tirets, des points, etc.). effacez l'entrée de tous les caractères qui ne sont pas des chiffres pour pouvoir stériliser l'entrée avec laquelle vous travaillez. Le moyen le plus simple consiste à utiliser une expression RegEx.

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

Ensuite, la réponse que vous avez énumérée devrait fonctionner dans la plupart des cas.

Pour répondre à votre question concernant votre problème de poste, vous pouvez supprimer tout ce qui est plus long que la longueur attendue de dix (pour un numéro de téléphone ordinaire) et l'ajouter à la fin à l'aide de

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

Vous voudrez faire un "si" pour déterminer si la longueur de votre entrée est supérieure à 10 avant de le faire, sinon utilisez simplement:

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

Utilisez Match dans Regex pour scinder, puis créez une chaîne formatée avec match.groups

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();
2
Sachin Ranadive

Ce qui suit fonctionnera sans utilisation d’expression régulière

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

Si nous n'utilisons pas long.Parse, le string.format ne fonctionnera pas.

2
Rama Krshna Ila

Essaye ça

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;

À votre santé.

2
Humberto Moreno
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;
}

La sortie sera: 001-568-895623

1
Mak

Veuillez utiliser le lien suivant pour C # http://www.beansoftware.com/NET-Tutorials/format-string-phone-number.aspx

Le moyen le plus simple de faire le format est d'utiliser 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;
}

Passez votre numéro de téléphone sous forme de chaîne 2021231234 jusqu'à 15 caractères.

FormatPhoneNumber(string phoneNum)

Une autre approche serait d’utiliser Substring

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;
    }
1
Mohammed Hossen

Je ne voulais pas ressusciter une vieille question, mais je pensais pouvoir proposer au moins une méthode légèrement plus facile à utiliser, même si elle était un peu plus complexe.

Donc, si nous créons un nouveau formateur personnalisé, nous pouvons utiliser le formatage plus simple de string.Format sans avoir à convertir notre numéro de téléphone en un long

Commençons par créer le formateur personnalisé:

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;
        }
    }
}

Donc si vous voulez utiliser ceci, vous feriez quelque chose comme ceci:

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

Quelques autres points à considérer:

À l'heure actuelle, si vous avez spécifié un formateur plus long qu'une chaîne à formater, il ignorera simplement les signes # supplémentaires. Par exemple, ceci String.Format(new NumericStringFormatter(),"{0:###-###-####}", "12345"); donnerait 123-45 - vous voudrez peut-être qu'il prenne une sorte de caractère de remplissage possible dans le constructeur.

De plus, je n'ai pas fourni de moyen d'échapper à un signe #, donc si vous vouliez l'inclure dans votre chaîne de sortie, vous ne pourriez pas le faire tel qu'il est actuellement.

La raison pour laquelle je préfère cette méthode à Regex est que j’ai souvent besoin de permettre aux utilisateurs de spécifier le format eux-mêmes et il m’est beaucoup plus facile d’expliquer comment utiliser ce format que d’essayer d’enseigner à un utilisateur regex.

De plus, le nom de la classe est un peu abusif, car il fonctionne réellement pour formater n’importe quelle chaîne tant que vous voulez la garder dans le même ordre et y insérer simplement des caractères.

0
Kent Cooper

Pour prendre soin de votre problème d'extension, que diriez-vous:

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

Vous pouvez essayer {0: (000) 000 - ####} si votre numéro cible commence par 0.

0
Alice Guo