Insert characters into a string in C#

14,397

Solution 1

How about:

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

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

Solution 2

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.

Solution 3

Do you care about performance on large strings?

var result = string.Join(".", str.Select(c => c.ToString());

Solution 4

This is my proposition, I know it does not looks super sexy, but I believe it's faster (3X faster for the sample string) and requires the exact amount of memory than all the ones using Select, Join, and all that jazz :-)

static string ConvertString(string s)
{
    char[] newS = new char[s.Length * 2 + 1];
    int i = 0;
    do
    {
        newS[i] = s[i / 2];
        if (i == (s.Length * 2 - 2))
            break;

        i++;
        newS[i] = '.';
        i++;
    }
    while (true);
    return new string(newS);
}

Plus it does not require the Framework 4.

Share:
14,397

Related videos on Youtube

Villager
Author by

Villager

Updated on June 04, 2022

Comments

  • Villager
    Villager almost 2 years

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

  • Quintin Robinson
    Quintin Robinson over 12 years
    +1 -- Might improve efficiency by doing StringBuilder sb = new StringBuilder(s.Length * 2);
  • svick
    svick over 12 years
    I think you're missing the final ..
  • BrokenGlass
    BrokenGlass over 12 years
    @svick: I do - but then again requirements were vague - text says "in-between each character" but example shows dot after last character
  • Snowbear
    Snowbear over 12 years
    Then string.Concat. We're even :)
  • Henk Holterman
    Henk Holterman over 12 years
    For problems of the same size as the example a StringBuilder is unnecessary and cumbersome.