Skip to main content
Known Participant
August 11, 2010
Question

Manipulating single characters inside a string?

  • August 11, 2010
  • 2 replies
  • 397 views

Hello CF Experts,

I feel a little stupid having to ask this, but I might be suffering from mental block:

I need to manipulate single characters inside a string. Lets say I have a string "-----" (5 hyphens) and

I want to replace the hyphen at position #pos# with "X".

I tried using the Mid() function, but that apparently is read-only:

     <cfset Mid(string,#pos#,1) = "X">   

results in an error.

Of course I can do string concatenation like

     <cfset string = Mid(string,1,#pos#-1) & "X" & Mid(string,#pos#+1,Len(string)-#pos#)

or use the Insert/RemoveChars functions:

     <cfset string = Insert("X",string,#pos#-1)>

     <cfset string = RemoveChars(string,#pos#+1,1)>

but this seems awfully awkward.

There must be a more elegant solution. Any hints?

Regards, Richard

This topic has been closed for replies.

2 replies

rspitzmdAuthor
Known Participant
August 12, 2010

Found what I was looking for at cflib.org:

http://www.cflib.org/udf/ReplaceAt

Inspiring
August 11, 2010

Strings are immutable, so one can't "edit" one, all one can do is create a new one based on an existing one.  So your insert() / removechars() approach is fine.  Or one could use left() & mid() (or right()), or replace() or... all variations on a fairly similar theme.

(http://en.wikipedia.org/wiki/Immutable_object#Java)

--

Adam