Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

String.Insert - insert a separator on given positions

0.00/5 (No votes)
18 Apr 2012CPOL 9.4K  
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)