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>

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson