Skip to main content
Participating Frequently
July 15, 2008
Question

Formatting a string?

  • July 15, 2008
  • 2 replies
  • 349 views
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
This topic has been closed for replies.

2 replies

Inspiring
July 15, 2008
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
Inspiring
July 15, 2008
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.