.net - C#在字符串中添加一个字符

标签 .net string visual-studio-2008 char c#-3.0

我知道我可以附加到一个字符串,但我希望能够在字符串中的每 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/

相关文章:

c# - Visual Studio 2015 : error building solution

c# - 如何在 C#/.NET 中使用 LINQ 表达式树调用 lambda

C...字符串分割问题

c - 如何使用换行符作为分隔符用字符串填充链表?

c++ - VS C++ 2008 : Modifying Output text?

c# - "cannot be marshaled by the runtime marshaler"是什么意思?

c# - 从 Ubuntu 使用 C# 访问网络路径

设置 DataSource 属性时,c# Items 集合无法修改

string - 如果字符串值是其他字符串的一部分,则从 QStringList 中删除字符串

c++ - 构建输出与项目构建顺序不匹配