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".
regex가 훨씬 더 잘 작동할 수도 있지만, 이전 프로그래밍 인용문을 기억하십시오.
어떤 사람들은 문제에 직면했을 때 "알아요, 규칙적인 표현을 쓸 거예요"라고 생각합니다.이제 그들에게는 두 가지 문제가 있습니다.
Zawinski --Jamie Zawinski, comp.lang.emacs
저는 규칙적인 표현을 선호합니다.
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);
저는 이것을 미국 번호에 대한 깨끗한 해결책으로 제안합니다.
public static string PhoneNumber(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
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}) {1}-{2}",
phoneNumber.Substring(0, 3),
phoneNumber.Substring(3, 3),
phoneNumber.Substring(6));
이것은 데이터가 올바르게 입력되었다고 가정하며, 정규식을 사용하여 검증할 수 있습니다.
작동해야 합니다.
String.Format("{0:(###)###-####}", Convert.ToInt64("1112224444"));
OR의 경우:
String.Format("{0:###-###-####}", Convert.ToInt64("1112224444"));
당신이 얻을 수 있다면.i["MyPhone"]
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
다음을 시도해 볼 수도 있습니다.
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.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
string phoneNum;
string phoneFormat = "0#-###-###-####";
phoneNum = Convert.ToInt64("011234567891").ToString(phoneFormat);
var p = "1234567890";
var formatted = $"({p[0..3]}) {p[3..6]}-{p[6..10]}"
출력 : (123) 456-7890
이거 먹어봐요.
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에서 Match를 사용하여 분할한 다음 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();
다음은 정규식을 사용하지 않고 작동합니다.
string primaryContactNumber = !string.IsNullOrEmpty(formData.Profile.Phone) ? String.Format("{0:###-###-####}", long.Parse(formData.Profile.Phone)) : "";
오래 안 쓰면.구문 분석, 문자열.형식이 작동하지 않습니다.
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;
}
전화번호를 문자열 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;
}
대상 번호가 0으로 시작하는 경우 {0: (000) 000-####}을(를) 시도할 수 있습니다.
여기 또 다른 방법이 있습니다.
public string formatPhoneNumber(string _phoneNum)
{
string phoneNum = _phoneNum;
if (phoneNum == null)
phoneNum = "";
phoneNum = phoneNum.PadRight(10 - phoneNum.Length);
phoneNum = phoneNum.Insert(0, "(").Insert(4,") ").Insert(9,"-");
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());
그 밖에 생각해야 할 몇 가지 사항:
지금 당장은 문자열을 포맷할 때보다 더 긴 형식을 지정했다면 추가 # 기호는 무시됩니다.를 들어 이를어은은rString.Format(new NumericStringFormatter(),"{0:###-###-####}", "12345");
할 수 .123-4가. 따라서 생성자에서 가능한 필러 특성을 사용하도록 설정할 수 있습니다.
또한 # 기호를 피할 수 있는 방법을 제공하지 않았기 때문에 출력 문자열에 이를 포함시키려면 현재 상태로는 사용할 수 없습니다.
Regex보다 이 방법을 선호하는 이유는 종종 사용자가 직접 포맷을 지정할 수 있도록 요구하는 사항이 있고 사용자 regex를 가르치려고 하는 것보다 이 포맷을 사용하는 방법을 설명하는 것이 훨씬 쉽기 때문입니다.
또한 클래스 이름은 실제로 문자열을 동일한 순서로 유지하고 그 안에 문자를 주입하는 형식으로 작동하기 때문에 약간의 잘못된 이름입니다.
Label12.Text = Convert.ToInt64(reader[6]).ToString("(###) ###-#### ");
이것이 나의 본보기입니다!이 일에 도움이 되었으면 좋겠습니다.안부 전해요
static void Main(string[] args)
{
Regex phonenumber = new(@"([0-9]{11})$");
Console.WriteLine("Enter a Number: ");
var number = Console.ReadLine();
if(number.Length == 11)
{
if (phonenumber.IsMatch(number))
{
Console.WriteLine("Your Number is: "+number);
}
else
Console.WriteLine("Nooob...");
}
else
Console.WriteLine("Nooob...");
}
null 체크가 포함된 @JonSket 답변의 개선된 버전이며 확장 방법이 있습니다.
public static string ToTelephoneNumberFormat(this string value, string format = "({0}) {1}-{2}") {
if (string.IsNullOrWhiteSpace(value))
{
return value;
}
else
{
string area = value.Substring(0, 3) ?? "";
string major = value.Substring(3, 3) ?? "";
string minor = value.Substring(6) ?? "";
return string.Format(format, area, major, minor);
}
}
언급URL : https://stackoverflow.com/questions/188510/how-to-format-a-string-as-a-telephone-number-in-c-sharp
'sourcecode' 카테고리의 다른 글
ctrl+c를 사용하여 python 중지 (0) | 2023.09.11 |
---|---|
괄호와 비교했을 때 어떤 차이가 있습니까? WHERE (a, b)= (1,2) (0) | 2023.09.11 |
문자열의 특정 문자 뒤에 있는 문자를 제거한 다음 부분 문자열을 제거하시겠습니까? (0) | 2023.09.11 |
분기를 병합한 후 삭제해야 합니까? (0) | 2023.09.11 |
WC_Product protected data 접근하기 3 (0) | 2023.09.11 |