复合字符串格式化(即:在VB6中使用字符串中的{0},{1}和{2})

时间:2012-10-22 12:45:34

标签: c# .net vb.net string vb6

如此处所述(复合格式字符串:http://msdn.microsoft.com/en-us/library/txafckwd.aspx)用于VB.NET和C#.NET(.NET Framework)。

但是,我还没有在任何地方看到过这个版本,谷歌没有回复任何有用的东西。

以下是我想要做的.NET Framework(VB.NET和C#.NET)的一些示例代码,但在VB6中:

在VB.NET中:

Dim myName As String = "Fred" 
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now)

在C#中:

string myName = "Fred";
String.Format("Name = {0}, hours = {1:hh}", myName, DateTime.Now);

如果有人知道如何在VB6中执行此操作,或者它存在于VB Classic的某个隐藏角落,我很想知道。感谢。

4 个答案:

答案 0 :(得分:7)

这个功能可以做你想做的事情

'Example:
Debug.Print FS("Name = {0}, Time = {1:hh:mm}, Number={2:#.00}", "My name", Now(), 12.5)

Function FS(strText As String, ParamArray values())
    Dim i As Integer
    i = 0

    For Each Value In values
        Dim intStart As Integer
        intStart = InStr(strText, "{" & i & "}")
        If intStart < 1 Then intStart = InStr(strText, "{" & i & ":")

        If intStart > 0 Then
            Dim intEnd As Integer
            intEnd = InStr(intStart, strText, "}")

            Dim strFormatedValue As String

            Dim intFormatPos As Integer
            intFormatPos = InStr(intStart, strText, ":")
            If intFormatPos < intEnd Then
                Dim strFormat As String
                strFormat = Mid(strText, intFormatPos + 1, intEnd - intFormatPos - 1)
                strFormatedValue = Format(Value, strFormat)
            Else
                strFormatedValue = Value
            End If

            strText = Left(strText, intStart - 1) & _
                      strFormatedValue & _
                      Mid(strText, intEnd + 1)

        End If
        i = i + 1
    Next

    FS = strText

End Function

答案 1 :(得分:2)

VB6中最接近NET复合格式的是运行时内置的Format函数 但是,它提供相同的功能还远远不够 在我看来,除非你有非常简单的要求,否则你运气不好。

答案 2 :(得分:1)

在模拟C / C ++方面,您最好考虑一下,例如sprintf。如果你谷歌搜索“vb6 call sprintf”,有一些有用的文章,例如这个one

答案 3 :(得分:0)

如果这不仅仅是一个用VB6功能构建的学术问题,那么替换和格式化。它们都没有.NET Format功能那么强大。你可以轻松自己滚动。写下自定义函数并将其添加到重复使用的方法的.bas文件中。然后,您可以通过添加.bas文件将您喜欢的方法添加到项目中。这是一个可以类似于.NET格式函数使用的函数。

Public Function StringFormat(ByVal SourceString As String, ParamArray Arguments() As Variant) As String
   Dim objRegEx As RegExp  ' regular expression object
   Dim objMatch As Match   ' regular expression match object
   Dim strReturn As String ' the string that will be returned

   Set objRegEx = New RegExp
   objRegEx.Global = True
   objRegEx.Pattern = "(\{)(\d)(\})"

   strReturn = SourceString
   For Each objMatch In objRegEx.Execute(SourceString)
      strReturn = Replace(strReturn, objMatch.Value, Arguments(CInt(objMatch.SubMatches(1))))
   Next objMatch

   StringFormat = strReturn

End Function

示例:

StringFormat(“你好{0}。我希望你见{1}。他们都适用于{2}。{0}已经为{2}工作了15年。”,“布鲁斯”,“克里斯“,”凯尔“)

这里有类似的答案,VBScript: What is the simplest way to format a string?