我知道我可以附加到一个字符串,但我希望能够在字符串中的每 5 个字符后添加一个特定字符
由此
字符串 alpha = abcdefghijklmnopqrstuvwxyz
对此
字符串 alpha = abcde-fghij-klmno-pqrst-uvwxy-z
最佳答案
请记住,字符串是不可变的,因此您需要创建一个新字符串。
字符串是 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);
}
}
}
产生这个:
Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
关于.net - C#在字符串中添加一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3879710/