【问题标题】:C# adding a character in a stringC#在字符串中添加一个字符
【发布时间】:2011-04-22 05:42:09
【问题描述】:

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

从此 字符串 alpha = abcdefghijklmnopqrstuvwxyz

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

【问题讨论】:

  • 您不能追加到字符串,也不能将特定字符添加到字符串。不能修改字符串。您可以根据现有字符串创建一个新字符串。看似细微的差别,但它可能很重要。

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


【解决方案1】:

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

字符串是 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

【讨论】:

    【解决方案2】:

    我不得不做类似的事情,尝试通过添加:. 将一串数字转换为时间跨度。基本上我正在使用 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 -
    ...
    

    【讨论】:

      【解决方案3】:

      这是我的解决方案,不过分。

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

      【讨论】:

      • 为什么不使用 String.Insert() 函数?
      • @Thibault:我已更改为 string.Insert。我想我太喜欢上榜了...... :)
      • 错误,但是插入后,长度发生了变化,所以i += position 是错误的。不是吗?
      • 您的函数没有产生正确的结果:您的 for 索引增量应该是 i += (position + character.Length),因为插入 character 字符串会移动字符串中的索引。
      • 另一个问题:它提供了 O(n^2) 的性能,因为每次调用 Insert 时都会创建一个新的字符串实例(并复制整个字符串)。您需要改用 StringBuilder(它也支持插入。)
      【解决方案4】:
      string alpha = "abcdefghijklmnopqrstuvwxyz";
      string newAlpha = "";
      for (int i = 5; i < alpha.Length; i += 6)
      {
        newAlpha = alpha.Insert(i, "-");
        alpha = newAlpha;
      }
      

      【讨论】:

        【解决方案5】:

        在 emailId 字段中每 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;
        }
        

        【讨论】:

          【解决方案6】:

          你可以定义这个扩展方法:

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

          【讨论】:

            【解决方案7】:
            string[] lines = Regex.Split(value, ".{5}");  
            string out = "";
            foreach (string line in lines)  
            {  
                out += "-" + line;
            }
            out = out.Substring(1);
            

            【讨论】:

            • 你可以使用Regex.Replace,或者String.Join,你为什么使用\d
            • 分配很多,效果不大。
            【解决方案8】:

            你可以用这个:

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

            与任何字符串完美配合。与往常一样,大小并不重要。 ;)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-10-08
              • 2013-10-27
              • 2020-12-18
              • 2012-08-28
              • 2020-04-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多