65.9K
CodeProject is changing. Read more.
Home

String.Insert - insert a separator on given positions

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Apr 18, 2012

CPOL
viewsIcon

9432

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:

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

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