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

本文关键字:添加 特殊字符 字符串 | 更新日期: 2023-09-27 18:12:41

我有一个字符串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;

谁能给我一个更好的解决方案

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

像这样:

  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中的第二个参数是长度,而不是位置

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;

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

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

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