I have some VB .NET software that interfaces to a load of old (but sound) COM objects. The VB provides a GU开发者_StackOverflowI for the COM objects, part of which consists of setting various options on the COM objects - several of which relate to string formatting.
I have a simple pair of VB .NET functions that convert basic %f, %d, %g formats to/from .NET equivalents using a large select case covering specific common strings, but they don't cover all formats. This is the kind of thing I have...
ElseIf f = "%.3f" Then
return "0.000"
ElseIf f = "%.2f" Then
return "0.00"
ElseIf f = "%.1f" Then
return "0.0"
Before I start diving in and making it more versatile with some parsing, does anyone know of a class (eg VB or C# .NET) that provides a decent ready-made implementation? Or perhaps some regexp wizadry could be used?
Many thanks
Tim
Do you really need both formats, or is one format adopted by your users and the other is used inside the implementation details of your software -- but could go away if you had string formatting functions that recognized your users' options directly?
You don't need to. Windows has that formatting built-in. You can simply P/Invoke wsprintf
from User32.dll.
Private Const _format_string = "\%(?<length>\d+)?(\.?(?<precision>\d+)?)(?<type>\w)"
Public Shared Function ToNet(format As String) As String
Dim regex As New Regex(_format_string, RegexOptions.IgnoreCase _
Or RegexOptions.CultureInvariant _
Or RegexOptions.IgnorePatternWhitespace _
Or RegexOptions.Compiled)
Dim m As Match = regex.Match(format)
Dim numberTypeFormat As String = String.Empty
Dim precision As Integer = 1
Dim precisionFieldName As String = "precision"
If m.Success Then
Select Case m.Groups("type").Value
Case "d", "i", "n", "u", "o"
numberTypeFormat = "D"
precisionFieldName = "length"
Case "x", "X"
numberTypeFormat = "X"
Case "f", "F"
numberTypeFormat = "N"
precision = 6
Case "e", "E"
numberTypeFormat = "E"
precision = 6
Case "s"
Throw New ArgumentException("String type format string not supported", "format")
End Select
If m.Groups(precisionFieldName).Success Then
precision = Integer.Parse(m.Groups(precisionFieldName).Value)
End If
Return String.Format("{0}{1}", numberTypeFormat, precision)
Else
Throw New ArgumentException("C++ Format string not recognized", "format")
Return String.Empty
End If
End Function
精彩评论