C# adding a character in a string

后端 未结 8 1887
长情又很酷
长情又很酷 2021-01-04 06:56

I know I can append to a string but I want to be able to add a specific character after every 5 characters within the string

from this string alpha = abcdefghijklmno

8条回答
  •  孤独总比滥情好
    2021-01-04 07:44

    You may define this extension method:

    public static class StringExtenstions
        {
            public static string InsertCharAtDividedPosition(this string str, int count, string character)
            {
                var i = 0;
                while (++i * count + (i - 1) < str.Length)
                {
                    str = str.Insert((i * count + (i - 1)), character);
                }
                return str;
            }
        }
    

    And use it like:

    var str = "abcdefghijklmnopqrstuvwxyz";
    str = str.InsertCharAtDividedPosition(5, "-");
    

提交回复
热议问题