Click here to Skip to main content
15,886,919 members
Articles / General Programming / String
Alternative
Tip/Trick

String.Insert - insert a separator on given positions

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Apr 2012CPOL 9.3K   3  
This is an alternative for "String.Insert - insert a separator on given positions"

Introduction

This is meant as an alternative tip to the original tip http://www.codeproject.com/Tips/368209/String-Insert-insert-a-separator-on-given-position, but in plain managed C#.

Using the code

The alternative code:

C#
public static string ExtInsertSep(this string s, string sep, params int[] pos)
{
    StringBuilder sb = new StringBuilder(s.Length + sep.Length * pos.Length);
    int from = 0;
    foreach (int i in pos.OrderBy(i=>i).Select(i=>i))
    {
        if (0 <= i && i < s.Length)
        {
            sb.Append(s.Substring(from, i - from));
            sb.Append(sep);
            from = i;
        }
    }
    sb.Append(s.Substring(from, s.Length - from));
    return sb.ToString();
}

Usage

C#
string res = "abcdefg".ExtInsertSep("..",2,4,6));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions

 
-- There are no messages in this forum --