Given the following string in C#, how would I insert a character in between each character in the string?
For example:
"Hello Sunshine"
would become
"H.e.l.l.o. .S.u.n.s.h.i.n.e"
What is the most efficient, fastest way of doing this in C#?
How about:
string result = string.Join(".", someString.AsEnumerable());
This hides most of the complexity, and will use a StringBuilder
internally.
If you want a dot after every character use a StringBuilder
:
StringBuilder sb = new StringBuilder(s.Length * 2);
foreach (char c in s) {
sb.Append(c);
sb.Append('.');
}
string result = sb.ToString();
If you don't want the trailing dot then in .NET 4.0 you can use string.Join
.
string result = string.Join(".", (IEnumerable<char>)s);
In .NET 3.5 and older the second parameter should be an array, meaning that you will have to temporarily create an array so it would most likely be faster to use the StringBuilder
solution shown above and treat the first or last index as a special case.
Note: Often you don't need the most efficient solution but just a solution that is fast enough. If a slightly slower but much simpler solution is sufficient for your needs, use that instead of optimizing for performance unnecessarily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With