如何在字符串中添加特殊字符

时间:2015-09-14 07:46:20

标签: c#

我有一个字符串7889875487我想将此字符串更改为(788)-987-5487。我正在尝试使用子字符串,但没有取得成功。

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;
有人请帮我解决更好的问题。

3 个答案:

答案 0 :(得分:3)

类似的东西:

  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

请注意,SubString中的第二个参数是长度,而不是位置

答案 1 :(得分:2)

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;

String.Substring(3, 5)的第二个参数是长度,而不是第二个索引

答案 2 :(得分:0)

您可以寻找正则表达式解决方案。

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

然后你的代码是:

string result = phoneFormating(mainStr);