Reputation: 4524
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.
Upvotes: 2
Views: 241
Reputation: 235
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);
Upvotes: 0
Reputation: 186843
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.
Upvotes: 3
Reputation: 46005
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
Upvotes: 2