2010-09-30 101 views
0

我有一些VB .NET軟件可以連接到一些舊的(但聲音很好的)COM對象。的VB提供了COM對象,其中一部分由設置在COM對象的各種選項的GUI - 其中一些涉及字符串格式化。將C++ printf格式轉換爲VB .NET字符串格式

我有一個簡單對,其將基本%F,%d,%G格式向/從使用大的情況下選擇特定覆蓋共同串.NET等效,但它們不覆蓋所有格式VB .NET函數。這是什麼樣的我有件事...

 ElseIf f = "%.3f" Then 
      return "0.000" 
     ElseIf f = "%.2f" Then 
      return "0.00" 
     ElseIf f = "%.1f" Then 
      return "0.0" 

之前,我開始跳水,使之更靈活一些解析,沒有人知道一個類(如VB或C#.NET)的,提供了一個體面現成的實施?或者也許可以使用一些正則表達式wizadry?

非常感謝

回答

1

你是否真的需要這兩種格式,或者是你的用戶所採取的一種格式,另一種是使用內部軟件的實現細節 - 但可能會消失,如果你有字符串格式化功能,可直接識別用戶的選項?

+0

.NET UI提供了常用格式的下拉列表,並嘗試選擇最佳匹配基礎COM對象中的printf格式的那個(上面的代碼對此是可以的)。但是,如果沒有匹配,我想向用戶顯示C++格式字符串以外的內容,這需要轉換爲顯示給用戶的格式。我曾經想過,一個.NET格式的字符串可以顯示給用戶,但也許有更好的解決方案? – ttt 2010-09-30 22:41:25

+0

好吧,你可以做得更像Microsoft Excel,當你拉起數字格式化對話框時,你可以先選擇General/Scientific/Percent/etc(例如'%f','%e'等等),然後輸入小數位的數目(其直接對應於printf風格格式字符串以及)。這肯定比printf格式的字符串更加用戶友好,並且可能比.NET格式的字符串更重要。有多少用戶會知道和'0.0#''0.00','#.00'之間的區別,? – 2010-09-30 23:58:25

0

你並不需要。 Windows具有內置的格式。你可以簡單的P/Invoke wsprintf從User32.dll中。

0
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