I have string variable declared globally.I have to append a substring to this string dynamically based on the user input.To do this I use str=str+substring;
In this case the string in str doesn’t have meaningful sentence finally ie.,there is no spaces between the words.to make it sense I used the following statement instead,
str=str+” “+substring; or str=str+substring+” “;
here everytime I have to append extra space to the substring before appending this to the main string were additional string processing is required.
Can anybody help on this were i can do this effectively?
It depends on how often you are doing it. If this is intermittent (or in fact pretty-much anything except a tight loop), then forget it; what you have is fine. Sure an extra string is generated occasionally (the combined substring/space), but it will be collected at generation 0; very cheap.
If you are doing this aggressively (in a loop etc), then use a
StringBuilderinstead:A final (unrelated) point – re “globally” – if you mean
static, you might want to synchronize access if you have multiple threads.