954,585 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

add character - into string

Hi.

I want to add character ' - ' in my string every 5th character.
For example:

123456789ABC would be like this --> 12345-6789A-BC

Already search in the internet but don't know how to do...
can anybody help me? Thanks in advance.

norul aswin
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

Try..

<cfscript>
	myString = "123456789ABC66HYIGG";
	myStringLength = len(trim(myString));
	breakPosition = 5;
	while(breakPosition < myStringLength)
	{
		myString = insert("-",myString,breakPosition);
		breakPosition = breakPosition + 6;
	}
</cfscript>
<cfoutput>#myString#</cfoutput>
@developer
Junior Poster in Training
70 posts since Nov 2010
Reputation Points: 13
Solved Threads: 10
 

thank you so much!! that is exactly i have to do.
Thanks:)

norul aswin
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

It's the right idea, but the logic breaks down for large strings like "123456789ABC66HYIGGasdfsdf ewqrdsfsdfsdfsd a111sdf134sa65d4asd4asd";

arrgh
Posting Whiz
381 posts since Dec 2008
Reputation Points: 32
Solved Threads: 47
 

This should fix those issues

<cfscript>
   str    = "123456789ABC66HYIGGasdfsdf ewqrdsfsdfsdfsd a111sdf134sa65d4asd4as";
   newStr = "";
   while (len(str)) {
      newStr = listAppend(newStr, left(str, 5), "-");
      str = removeChars(str, 1, 5);
   }
   WriteOutput(newStr);
</cfscript>
arrgh
Posting Whiz
381 posts since Dec 2008
Reputation Points: 32
Solved Threads: 47
 

Yes that would break on large strings..Was wondering what went wrong!My senior Dileep pointed it correctly..Actually the while condition wasn't correct. Have to check the string length each time. This would fix it..hope so.. :) .

<cfscript>
myString = "123456789ABC66HYIGGasdfsdfewqrdsfsdfsdfsda111sdf134sa65d4asUUJJUIP";
	breakPosition = 5;
	while(breakPosition < len(trim(myString)))
	{
		myString = insert("-",myString,breakPosition);
		breakPosition = breakPosition + 6;
	}
</cfscript>
<cfoutput>#myString#</cfoutput>
@developer
Junior Poster in Training
70 posts since Nov 2010
Reputation Points: 13
Solved Threads: 10
 

Yeah, I tried that one too. I think it works. But it did leave a trailing slash when the # of chars are divisible by 5 ...I think. I was too lazy to trim it. So I went with listAppend(). But insert's probably better performance :)

arrgh
Posting Whiz
381 posts since Dec 2008
Reputation Points: 32
Solved Threads: 47
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You