简体   繁体   中英

How add special char into string

I have a string 7889875487 I want to change this string into (788)-987-5487. I was trying with taking sub string but not getting success.

var mainStr = string.Empty;
var str1 = string.Empty;
var str2 = string.Empty;
var str3 = string.Empty;

 str1 = item.PrimaryPhoneNumber.ToString().Substring(0,3);
 str2 = item.PrimaryPhoneNumber.ToString().Substring(3, 5);
 str3 = item.PrimaryPhoneNumber.ToString().Substring(5);

 mainStr = "(" + str1 + ")" + "-" + str2 + "-" + str3;

someone please help me with better solution.

Something like that:

  String phone = item.PrimaryPhoneNumber.ToString();

  mainStr = String.Format("({0})-{1}-{2}",
    phone.SubString(0, 3), // starting from 0th, 3 characters length
    phone.SubString(3, 3), // starting from 3d, 3 characters length
    phone.SubString(6));   // starting from 6th, up to the end

note, that the second argument in SubString is length , not position .

try

string item = "7889875487";
string str1 = item.Substring(0, 3);
string str2 = item.Substring(3, 3);
string str3 = item.Substring(6);

string mainStr = "(" + str1 + ")" + "-" + str2 + "-" + str3;

the 2nd parameter of String.Substring(3, 5) is the length, not the 2nd index

You may look for a regex solution.

using System.Text.RegularExpressions;

private string phoneFormating(string unformatedString)
{
    Regex phone_reg = new Regex(@"^(\d\d\d)(\d\d\d)(\d\d\d\d)$");//you could write it like this too: (@"^(\d){3}(\d){3}(\d){4}$")
    Match m = phone_reg.Match(unformatedString);
    if (m.Success)//ie if your input string is 10 numbers only
    {
        string formatedString = "(" + m.Groups[1].Value + ")-" + m.Groups[2].Value + "-" + m.Groups[3].Value;
            return formatedString;
    }
    else {return string.Empty;}//or anything else.
}

then your code is:

string result = phoneFormating(mainStr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM