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

18

我知道可以将字符串附加在一起,但我想要能够在字符串中的每5个字符后添加一个特定的字符。

从这个 string alpha = abcdefghijklmnopqrstuvwxyz

到这个 string alpha = abcde-fghij-klmno-pqrst-uvwxy-z


3
不能向字符串追加内容,也不能向字符串添加特定字符。字符串是不可更改的。你可以基于现有字符串创建一个新的字符串。这似乎是微妙的不同,但它可能很重要。 - Michael Petrotta
1
与https://dev59.com/pXA75IYBdhLWcg3wboUz相关的编程内容。 - Matt Ellen
8个回答

26

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

字符串是可枚举的,因此您可以在其上运行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

15

我曾经遇到过类似的问题,需要将一串数字转换为时间段,通过添加:.来实现。基本上,我需要将 235959999 转换为 23:59:59.999。对我来说很容易,因为我知道在哪里需要“插入”这些字符。

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

基本上是将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 -
...

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, "-"));

4
为什么不使用String.Insert()函数? - Thibault Falise
@Thibault:我现在改用string.Insert了。我猜我太过于喜欢使用列表了... :) - danijels
1
错误,但是在插入之后,长度会发生变化,所以 i += position 是错误的。不是吗? - Kobi
2
你的函数没有产生正确的结果:你的for循环索引增量应该是i +=(position + character.Length),因为插入character字符串会使字符串中的索引发生偏移。 - Thibault Falise
2
另一个问题是:由于每次调用Insert都会创建一个新的字符串实例(并复制整个字符串),因此它会导致O(n^2)的性能问题。你需要使用StringBuilder代替(它也支持Insert)。 - jammycakes
显示剩余3条评论

4
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
  newAlpha = alpha.Insert(i, "-");
  alpha = newAlpha;
}

1
在电子邮件ID字段中每8个字符插入一个空格。
public string BreakEmailId(string emailId) {
    string returnVal = string.Empty;
    if (emailId.Length > 8) {           
        for (int i = 0; i < emailId.Length; i += 8) {
            returnVal += emailId.Substring(i, 8) + " ";
        }
    }

    return returnVal;
}

0
string[] lines = Regex.Split(value, ".{5}");  
string out = "";
foreach (string line in lines)  
{  
    out += "-" + line;
}
out = out.Substring(1);

你可以使用 Regex.ReplaceString.Join,而为什么要使用 \d - Kobi
很多分配,不太有效。 - Dmitry Karpezo

0
您可以定义这个扩展方法:
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;
        }
    }

并像这样使用:

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

0

你可以使用这个:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;
    
for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

适用于任何字符串。一如既往,大小并不重要。 ;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接