Skip to main content
July 17, 2014
Answered

Get every 2nd character of a string

  • July 17, 2014
  • 2 replies
  • 320 views

Hi,

Do you know what's CF function do I need to get every 2nd character of a string?  Basically, I have a string: w3f587j8a9.  I want to get every 2nd, 4th, 6th, 8th, 10th, ect...  So the result would be 35789.  Of course the limit of the loop will be like 4 characters or something like that.

Thanks.

This topic has been closed for replies.
Correct answer Endboss_ZA

Something like this you mean?

<cfset str = "w3f587j8a9">

<cfset newstr="">

<cfloop from="0" to="#len(str)#" index="i" step="2">

    <cfif i gt 0><cfset newstr &=mid(str,i,1)></cfif>

</cfloop>

   

<cfoutput>#newstr#</cfoutput>

2 replies

BKBK
Community Expert
Community Expert
July 17, 2014

An alternative that borrows from Endboss_ZA and from Java's String API, remembering that arguments for charAt start at 0:

<cfset str = "w3f587j8a9">

<cfset newstr="">

<cfloop from="1" to="#int(len(str)/2)#" index="i">

    <cfset newstr &=str.charAt(2*i-1)>

</cfloop>

<cfoutput>#newstr#</cfoutput>

Endboss_ZACorrect answer
Inspiring
July 17, 2014

Something like this you mean?

<cfset str = "w3f587j8a9">

<cfset newstr="">

<cfloop from="0" to="#len(str)#" index="i" step="2">

    <cfif i gt 0><cfset newstr &=mid(str,i,1)></cfif>

</cfloop>

   

<cfoutput>#newstr#</cfoutput>