just as the question says. I get numbers like 2125550938 or 20298277625552. these should change to (212) 555-0938 and (202) 982-7762 x 5552 respectively. this is in vb.net
A:
Dim newNumber As New String
If number.Length = 10 Then
newNumber = "(" & number.Substring(0, 3) & ") " & number.Substring(2, 3) & "-" & number.Substring(5, 4)
ElseIf number.Length = 14 Then
newNumber = "(" & number.Substring(0, 3) & ") " & number.Substring(2, 3) & "-" & number.Substring(5, 4) & " x " & number.Substring(9)
End if
Kyra
2010-06-21 20:40:06
I would change Length = 14, to Length > 10
maxwellb
2010-06-21 20:42:57
A:
for kyra - the error i am getting is "Index and length must refer to a location within the string. Parameter name: length" newnumber = 2125122121
lkre
2010-06-21 20:50:17
oops. Sorry I was thinking about another language where substring is specified from start to end index. In VB though it is specified from start index and the second number is the length. I changed the numbers in the substring in my answer but I haven't tested it. More about the substring function can be found here : http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Kyra
2010-06-22 14:00:13
A:
I would probably go with an implementation of regular expressions, something like this:
Dim phoneNumbers() As String = {"2125550938", _
"20298277625552", _
"2025551212378", _
"202555131345943"}
Dim ext As String = ""
Dim r As New Regex("^(?<AC>\d{3})(?<First>\d{3})(?<Last>\d{4})(?<Ext>\d*$)")
Dim m As Match
For i As Int32 = 0 To (phoneNumbers.Length - 1)
m = r.Match(phoneNumbers(i))
If m.Groups("Ext").Length > 0 Then
ext = " x " & CStr(m.Groups("Ext").Value)
Else
ext = ""
End If
Console.WriteLine("({0}) {1}-{2}{3}", _
CStr(m.Groups("AC").Value), _
CStr(m.Groups("First").Value), _
CStr(m.Groups("Last").Value), ext)
Next
Console.Read()
This would allow for phone numbers without extensions or with a variable length extension.
Hope that helps. - Jeff
knslyr
2010-06-22 14:52:15