CFLib.org – Common Function Library Project

string2linesArray(inString)

Last updated July 11, 2005

author

Massimo Foti

Version: 1 | Requires: CF6 | Library: StrLib

Description:
Turn a string into an array of lines, using java.io.BufferedReader to maximize performance.

Return Values:
Returns an array.

Example:

<!--- Create a multi-line string --->
<cfsavecontent variable="myString">Ciao Mammma,
manda soldi...
mandali presto.
Grazie.

Baci
Massimo
</cfsavecontent>

<cfdump var="#string2linesArray(myString)#">

Parameters:

Name Description Required
inString The string to parse. Yes

Full UDF Source:

<!---
 Turn a string into an array of lines.
 
 @param inString 	 The string to parse. (Required)
 @return Returns an array. 
 @author Massimo Foti (massimo@massimocorner.com) 
 @version 1, August 15, 2005 
--->
<cffunction name="string2linesArray" output="false" returntype="array" hint="Turn a string into an array of lines, using java.io.BufferedReader to maximize performances">
	<cfargument name="inString" type="string" required="yes" hint="Incoming string">
	<cfscript>
	var linesArray = ArrayNew(1);
	var jReader = createObject("java","java.io.StringReader").init(arguments.inString);
	var jBuffer = createObject("java","java.io.BufferedReader").init(jReader);
	var line = jBuffer.readLine();	
	</cfscript>
	<cftry>
	<!--- 
	Unlike Java, CFML has no notion of null, but this is quite a special case. 
	Whenever readLine() reach the end of the file, it return a Java null, 
	as soon as the BufferedReader return null, ColdFusion "erase" the line variable, making it undefined. 
	Here we leverage this somewhat weird behavior by using it as test condition for the loop
	 --->
		<cfloop condition="#IsDefined("line")#">
			<cfset ArrayAppend(linesArray, line)>
			<cfset line=jBuffer.readLine()>
		</cfloop>
		<cfset jBuffer.close()>
		<cfcatch type="any">
			<!--- Something went wrong; we better close the stream anyway, just to be safe and leave no garbage behind --->
			<cfset jBuffer.close()>
			<cfthrow message="string2linesArray: Failed to read lines from string" type="string2linesArray">
		</cfcatch>
	</cftry>
	<cfreturn linesArray>
</cffunction>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson