0

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.

3
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by arrgh
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>
0

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

0

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>
0

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>
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.