Forum Moderators: open

Message Too Old, No Replies

Add to a string

How to add to a string when looping

         

MavisCruet

5:41 pm on Mar 28, 2008 (gmt 0)

10+ Year Member



Hi,

In PHP if you want to add to a string rather than replace it, you just use

while (expr) {
$string .= 'this'
}

So if the loop ran 3 times, you would get a string of 'thisthisthis'.

How do you do this in ASP?
All the examples I have found only show loops using response.write at the looping action - I need to set a variable.

[edited by: MavisCruet at 5:53 pm (utc) on Mar. 28, 2008]

marcel

7:20 pm on Mar 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The easy way is

myString += "this"

but this way is not very efficient when building long strings, you should use a string builder instead:

VB:
Dim myStringBuilder As StringBuilder = New StringBuilder
myStringBuilder.Append("this")

C#
StringBuilder myStringBuilder = new StringBuilder();
myStringBuilder.Append("this");

Demaestro

7:26 pm on Mar 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I don't know Marcel, do you really think importing an entire class to concatenate strings is more efficient?

Maybe it is better to do in VB because of how it cleans up variables in memory, I don't know it has been about 6 years since I did a project in ASP, but to me that seems like a lot of overhead to reinvent the wheel.

marcel

7:48 pm on Mar 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I should have said '...when building very long strings...' :) If you're only planning on a few iterations it doesn't really matter.

Here is some more info, the bottom post is quite interesting:
[weblogs.asp.net...]

Demaestro

8:03 pm on Mar 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Good info thanks marcel