C#在字符串中添加字符 [英] C# adding a character in a string

查看:2592
本文介绍了C#在字符串中添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

从此
字符串alpha = abcdefghijklmnopqrstuvwxyz

from this string alpha = abcdefghijklmnopqrstuvwxyz

对此
字符串alpha = abcde-fghij-klmno-pqrst-uvwxy-z

to this string alpha = abcde-fghij-klmno-pqrst-uvwxy-z

推荐答案

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

Remember a string is immutable so you will need to create a new string.

字符串是IEnumerable的,因此您应该能够对其进行for循环

Strings are IEnumerable so you should be able to run a for loop over it

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

这篇关于C#在字符串中添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆