C#在字符串中添加一个字符

pab*_*sal 12 .net visual-studio-2008 c#-3.0

我知道我可以附加到一个字符串,但我希望能够在字符串中每5个字符后添加一个特定的字符

从这个字符串alpha = abcdefghijklmnopqrstuvwxyz

到这个字符串alpha = abcde-fghij-klmno-pqrst-uvwxy-z

Pre*_*gha 19

请记住,字符串是不可变的,因此您需要创建一个新字符串.

字符串是IEnumerable,所以你应该能够在它上面运行for循环

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string alpha = "abcdefghijklmnopqrstuvwxyz";
            var builder = new StringBuilder();
            int count = 0;
            foreach (var c in alpha)
            {
                builder.Append(c);
                if ((++count % 5) == 0)
                {
                    builder.Append('-');
                }
            }
            Console.WriteLine("Before: {0}", alpha);
            alpha = builder.ToString();
            Console.WriteLine("After: {0}", alpha);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产生这个:

Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
Run Code Online (Sandbox Code Playgroud)


dan*_*els 11

这是我的解决方案,没有过度使用它.

    private static string AppendAtPosition(string baseString, int position, string character)
    {
        var sb = new StringBuilder(baseString);
        for (int i = position; i < sb.Length; i += (position + character.Length))
            sb.Insert(i, character);
        return sb.ToString();
    }


    Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));
Run Code Online (Sandbox Code Playgroud)

  • 为什么不使用String.Insert()函数? (4认同)
  • 你的函数没有产生正确的结果:你的索引增量应该是`i + =(position + character.Length)`因为插入`character`字符串会移动字符串中的索引. (2认同)
  • 另一个问题是:它会产生O(n ^ 2)性能,因为每次调用Insert时都会创建一个新的字符串实例(并复制整个字符串).您需要使用StringBuilder(它也支持Insert). (2认同)

Noc*_*nix 9

我不得不做类似的事情,尝试通过添加:和来将一串数字转换为时间跨度..基本上我采取235959999并需要将其转换为23:59:59.999.对我来说这很容易,因为我知道我需要"插入"所说的角色.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");
Run Code Online (Sandbox Code Playgroud)

基本上用插入的字符重新分配ts给自己.我从后到前工作,因为我很懒,不想为其他插入的字符做额外的数学运算.

你可以尝试类似的东西:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...
Run Code Online (Sandbox Code Playgroud)