【问题标题】:How to format a fixed length string如何格式化固定长度的字符串
【发布时间】:2022-02-01 11:05:32
【问题描述】:

我有一个固定长度的字符串ABCDEFGHIJK,有没有办法使用字符串格式将其转换为AB-CDEFGHIJ-K

【问题讨论】:

  • 使用.Substring 将字符串分成多个部分,然后在将其重新构建为单个字符串时添加连字符。
  • 因为这是一个简单的问题,是的,有很多方法可以做到。我投票结束这个问题太宽泛了,因为除非你为问题增加一些范围或提供一些对你不起作用的代码,否则这只会变成单一语言Code Golf
  • var s = "ABCDEFGHIJK".Insert(2, "-").Insert(11, "-");
  • 是的,这是一个简单的问题,我想知道是否可以使用字符串格式。代码没有错误,只是想要知识

标签: c# string


【解决方案1】:
var s = "ABCDEFGHIJK";

Console.WriteLine($"{s[..2]}-{s[2..10]}-{s[^1..]}");

【讨论】:

    【解决方案2】:

    我有一个固定长度的字符串 ABCDEFGHIJK,有没有办法转换 这个用字符串格式转换成 AB-CDEFGHIJ-K 吗?

    关注“字符串格式”部分,我们可以实现IFormatProvider。如果字符串长度正好是 11 个字符,这将格式化字符串,否则它只会返回相同的字符串。按照例子,“H”格式代表“hypenated”:

    private void button1_Click_2(object sender, EventArgs e)
    {
        string input = "ABCDEFGHIJK";
        string output = String.Format(new MyStringFormat(), "Formatted: {0:H}", input);
        Console.WriteLine(input);
        Console.WriteLine(output);
    }
    
    public class MyStringFormat : IFormatProvider, ICustomFormatter
    {
        
        object IFormatProvider.GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
            {
                return this;
            }
            else
            {
                return null;
            }
        }
    
        string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (arg.GetType() != typeof(String))
            {
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
                }
            }
    
            string ufmt = format.ToUpper(CultureInfo.InvariantCulture);
            if (ufmt != "H")
            {
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
                }
            }
    
            string result = arg.ToString();
            if (result.Length != 11)
                return result;                
            else
                return result.Insert(2, "-").Insert(11, "-"); // see comment by Hans Passant!
        }
    
        private string HandleOtherFormats(string format, object arg)
        {
            if (arg is IFormattable)
                return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
            else if (arg != null)
                return arg.ToString();
            else
                return String.Empty;
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      怎么样

      var newstring = String.format("{0}-{1}-{2}", s.Substring(0,2), s.Substring(3,7), s.Substring(10,1))
      

      你也可以使用插值和新范围的东西

      【讨论】:

        【解决方案4】:

        var f = Regex.Replace("ABCDEFGHIJK", "^(..)(.*)(.)$", "$1-$2-$3");

        ...是的,我知道。

        此外,删除 {2} 等的灵感来自于 Yuriy 的回答 here

        【讨论】:

        • 过去的答案哈哈哈。有趣的是,我已经 12 年没有改变了。
        【解决方案5】:

        也许是鲁布·戈德堡的方式:

            static void Main(string[] args)
            {
                string code = "ABCDEFGHIJK";
                string mask = "##-########-#";
        
                Console.WriteLine(code.Format(mask));
                // AB-CDEFGHIJ-K
            }
        
            public static string Format(this string code, string mask, char token = '#')
            {
                StringBuilder sb = new StringBuilder(mask.Length);
                int index = 0;
                foreach (var item in mask)
                {
                    if (item==token)
                    {
                        sb.Append(code[index++]);
                    }
                    else
                    {
                        sb.Append(item);
                    }
                }
                return sb.ToString();
            }
        

        编辑 1

        将空格 ' ' 字符占位符替换为井号 '#' 以提高清晰度。

        【讨论】:

          猜你喜欢
          • 2017-04-30
          • 2012-01-15
          • 2018-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-04
          • 1970-01-01
          相关资源
          最近更新 更多