Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert characters into a string in C#

Tags:

string

c#

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#?

like image 213
Villager Avatar asked Dec 12 '22 07:12

Villager


2 Answers

How about:

string result = string.Join(".", someString.AsEnumerable());

This hides most of the complexity, and will use a StringBuilder internally.

like image 99
BrokenGlass Avatar answered Dec 30 '22 23:12

BrokenGlass


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.

like image 29
Mark Byers Avatar answered Dec 30 '22 23:12

Mark Byers