[removed] What is the simplest way to format a string?

前端 未结 5 1321
感情败类
感情败类 2020-11-29 10:36

I have the following format: Value1 is {0} and Value2 is {1}.

I need to replace the numbers in the brackets with strings. This is easily done in most languages usin

5条回答
  •  粉色の甜心
    2020-11-29 11:08

    I wanted something similar and didn't like any of these answers as they meant multiple lines for each value (Ignoring Beaner's answer is for the wrong language!) so I created the following:

    Public Function StrFormat(FormatString, Arguments())
        Dim Value, CurArgNum
    
        StrFormat = FormatString
    
        CurArgNum = 0
        For Each Value In Arguments
            StrFormat = Replace(StrFormat, "{" & CurArgNum & "}", Value)
            CurArgNum = CurArgNum + 1
        Next
    End Function
    

    You can use the following then (note that you need to add "Array()" around your variables):

    formatString = "Test '{0}', '{2}', '{1}' and {0} again!"
    Response.Write StrFormat(formatString, Array(1, 2, "three", "Unused"))
    Response.Write StrFormat(formatString, Array(4, 5, "six", "Unused"))
    

    Which will output what you expect:

    Test '1', 'three', '2' and 1 again!
    Test '4', 'six', '5' and 4 again!
    

    Hope this feels a bit more natural for people from other languages.

提交回复
热议问题