2 Replies Latest reply on Jul 15, 2008 1:21 PM by Stressed_Simon

    Formatting a string?

    rpeters1983 Level 1
      I'm trying to format a string for a query using cfscript. Instead of using &'s to concatenate a string, is there a method in CF that is similar to .NET's String.Format method or php's sprintf function? Thanks.

      Ryan
        • 1. Re: Formatting a string?
          Dan Bracuk Level 5
          I don't know what those functions do, but if you don't like the concat operator, you can use octothorps inside quotes for the variable part of your string.

          Since you mentioned that you will eventually use this string inside your query, the PreserveSingleQuotes function might be relevent.
          • 2. Re: Formatting a string?
            Stressed_Simon Level 1
            You can just use the # symbols inside quotes, e.g.
            <cfset fName = "Simon">
            <cfset lName = "Baynes">
            <cfset withAnds = fName & " " & lName>
            <cfset withoutAnds = "#fName# #lName#">

            Those produce the same results.

            Also you can use Java.
            <cfset oBuilder = createObject("java", "java.lang.StringBuilder").init()>
            <cfset oBuilder.append(fName)>
            <cfset oBuilder.append(" ")>
            <cfset oBuilder.append(lName)>
            <cfset javaWay = oBuilder.toString()>

            If you are doing lots of concatenation then I recommend the java option, because Strings are immutable. This means that once assigned they cannot be changed, so when you do a concatenation you are actually creating a new object in memory. Which is what the StringBuilder overcomes, so if you are doing appending in a loop for example this will be quicker and less memory intesive.

            HTH