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.

Recommended Answers

All 6 Replies

Try..

<cfscript>
	myString = "123456789ABC66HYIGG";
	myStringLength = len(trim(myString));
	breakPosition = 5;
	while(breakPosition < myStringLength)
	{
		myString = insert("-",myString,breakPosition);
		breakPosition = breakPosition + 6;
	}
</cfscript>
<cfoutput>#myString#</cfoutput>

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

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

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>

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>

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.