开发者

string manipulations

开发者 https://www.devze.com 2023-01-21 10:27 出处:网络
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;

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 StringBuilder instead:

// declaration
StringBuilder sb = new StringBuilder();
...
// composition
sb.Append(' ').Append(substring);
...
// obtaining the string
string s = sb.ToString();

A final (unrelated) point - re "globally" - if you mean static, you might want to synchronize access if you have multiple threads.


What do you want to achieve exactly? You could store the words in a list

List<string> words = new List<string>();
...
words.Add(str);

And then delay the string manipulation (i.e. adding the spaces between words) until at the very end. This way, you're on the fly operation is just an add to a list, and you can do all the complex processing (whatever it may be) at the end.


If you are doing it rarely, you could slightly pretty up the code by doing:

str += " " + substring;

Otherwise, I'd go with Nanda's solution.


@Nanda: in your case you should use string builder.

StringBuilder data = new StringBuilder();
data.AppendFormat(" {0}", substring);
0

精彩评论

暂无评论...
验证码 换一张
取 消