Skip to main content
December 8, 2010
Question

insert comma at every third position in string...

  • December 8, 2010
  • 2 replies
  • 2138 views

I am flumoxed on something rather simple I fear.  I have a string like this ...

B01B09B20B21C13E10F07G12G20G24

I need to turn it into this

B01,B09,B20,B21,C13,E10,F07,G12,G20,G24

It is consistant in the following:

1. each segment will always be 3 characters long

2. each segment will always be structured as 1 character and 2 numerals

3. the list will always vary in length but always divisible by 3

Any simple solutions?  I have though about various cflooping methods and simply not liked anythign I cam up with.

All help is greatly appreciated.

God Bless!

Chris

    This topic has been closed for replies.

    2 replies

    December 8, 2010

    I only wish I could have given you both the 'correct' answer as both were correct.

    Thank you

    Chris

    12Robots
    Participating Frequently
    December 8, 2010

    Here are a couple options.  I prefer the first.

    <cfset string = "B01B09B20B21C13E10F07G12G20G24" />

    <cfset newstring = "" />

    <cfloop from="1" to="#len(string)#" index="i" step="3">

    <cfset newstring = listAppend(newstring, mid(string, i, 3), ",") />

    </cfloop>

    <cfoutput>#newstring#</cfoutput>

    ===========================================================================================

    <cfset string = "B01B09B20B21C13E10F07G12G20G24" />

    <cfset counter = 0 />

    <!--- Iterate length - 4 times (-4 so that it does not do a final loop and stick a comma on the end) --->

    <cfloop from="0" to="#len(string)-4#" index="i" step="3">

    <cfset string = insert(",", string, i+counter+3) />

    <cfset counter++ />

    </cfloop>

    <cfoutput>#string#</cfoutput>

    Inspiring
    December 8, 2010

    I don't think one needs to do all that looping about the place.

    s1 = "B01B09B20B21C13E10F07G12G20G24";

    s2 = reReplace(s1, "(.{3})\B", "\1,", "ALL");

    That's all one needs to do.

    As a rule of thumb, I find if one is confronted with a requirement to loop over a string to "do" something to it, then there's a good chance a regex operation will effect the same results.

    --

    Adam

    12Robots
    Participating Frequently
    December 8, 2010

    One would agree that that is a more elagant solutions. But one did not have the regex knowledge to create it.

    Regex is an awesome tool, but one would have to agree that it is not th most intuative.

    In this case oneone does not mind looping. Of course onetwo is welcome ot disagree.

    oneone