Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string manipulation

Status
Not open for further replies.

shukui

Technical User
Apr 27, 2001
28
US
Hi all,

How can I manipulate string like from

"acthaychyaggdsdy"

to

"act hay chy agg dsd y"

or change above string to a list or an array containing above elements.

Thanks,

Stephen
 
Browse at the string functions in the online docs . You need to extract one letter at a time. You could do:

<cfset string = &quot;acthaychyaggdsdy&quot;>
<cfset word = &quot;&quot;>
<cfset j = 1>

<cfset wordarray = arrayNew(1)>

<cfloop index=&quot;i&quot; from=&quot;1&quot; to=&quot;#len(string)#&quot;>
<cfset word = Insert(mid(string, i, 1), word, len(word))>

<cfif i mod 3 EQ 0>
<cfset wordarray[j] = word>
<cfset j = j + 1>
<cfset word = &quot;&quot;>
</cfif>

</cfloop>

<cfoutput>

<br>
<cfloop index=&quot;i&quot; from=&quot;1&quot; to=&quot;#arraylen(wordarray)#&quot;>
#wordarray#<br>
</cfloop>

</cfoutput>

There is a bug in the code. It doesn't get the last character. I'll leave the fix up to you.
 
Thank you A440Guy,

I figured it out this way:

<cfset string = &quot;acthaychyaggdsdy&quot;>
<CFLOOP INDEX=&quot;i&quot; FROM=&quot;#len(string)#&quot; TO=&quot;1&quot; step =&quot;-1&quot;>
<cfif (i mod 3) EQ 0>
<cfset string = Insert(' ', string, #i#)>
</cfif>
</CFLOOP>

Thank you for remind me the Insert() funcion.
 
Pretty clever!

OK, for those of you who are reading this, here is the solution to fix the bug mentioned above. Insert these lines after the end of the first CFLOOP:

<cfif word NEQ &quot;&quot;>
<cfset wordarray[j] = word>
</cfif>


 
What about using a regular expression instead

<CFSET string = &quot;acthaychyaggdsdy&quot;>
<CFSET string = Trim(ReReplace(string, &quot;(
Code:
[
Code:
[
:alpha:
Code:
]
Code:
]
{1,3})&quot;
, &quot;\1 &quot;, &quot;ALL&quot;))>
- tleish
 
That's much more compact. However, it _is_ harder to understand and should be accompanied by a cogent comment.
 
Yes, that is really elegence! How does it work, by the way?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top