2

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.

2
  • 1
    what result are you getting? Commented Sep 14, 2015 at 7:48
  • use string.Format instead of + Commented Sep 14, 2015 at 7:49

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

C# 6 please string mainStr = $"({item.Substring(0, 3)})-{item.Substring(3, 3)}-{item.Substring(6)}";
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.