简体   繁体   English

格式化字母数字字符串

[英]Formatting alphanumeric string

I have a string with 16 alphanumeric characters, eg F4194E7CC775F003. 我有一个包含16个字母数字字符的字符串,例如F4194E7CC775F003。 I'd like to format it as F419-4E7C-C775-F003. 我想将其格式化为F419-4E7C-C775-F003。

I tried using 我试过用

string.Format("{0:####-####-####-####}","F4194E7CC775F003");

but this doesn't work since it's not a numeric value. 但这不起作用,因为它不是数值。

So I came up with the following: 所以我想出了以下内容:

public class DashFormatter : IFormatProvider, ICustomFormatter
{
  public object GetFormat(Type formatType)
  {
    return this;
  }

  public string Format(string format, object arg, IFormatProvider formatProvider)
  {
    char[] chars = arg.ToString().ToCharArray();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < chars.Length; i++)
    {
      if (i > 0 && i % 4 == 0)
      {
        sb.Append('-');
      }

      sb.Append(chars[i]);
    }

    return sb.ToString();
  }
}

and by using 并通过使用

string.Format(new DashFormatter(), "{0}", "F4194E7CC775F003");

I was able to solve the problem, however I was hoping there is a better/simpler way to do it? 我能够解决问题,但是我希望有更好/更简单的方法来解决它? Perhaps some LINQ magic? 也许一些LINQ魔术?

Thanks. 谢谢。

You can do it in one line without Linq: 你可以在没有Linq的情况下在一行中完成:

        StringBuilder  splitMe = new StringBuilder("F4194E7CC775F003");
        string joined = splitMe.Insert(12, "-").Insert(8, "-").Insert(4, "-").ToString();

You could do it with a regular expression, though I don't know what the performance of this would be compared to the other methods. 您可以使用正则表达式来完成它,但我不知道将其性能与其他方法相比较。

string formattedString = Regex.Replace(yourString, "(\\S{4})\\B", "$1-");

You could put this in an extension method for string too, if you want to do: 你可以把它放在字符串的扩展方法中,如果你想这样做:

yourString.ToDashedFormat();

If you want it linq: 如果你想要它linq:

var formatted = string.Join("-", Enumerable.Range(0,4).Select(i=>s.Substring(i*4,4)).ToArray());

And if you want it efficient: 如果你想要它有效:

var sb = new StringBuilder(19);
sb.Append(s,0,4);
for(var i = 1; i < 4; i++ )
{
 sb.Append('-');
 sb.Append(s,i*4, 4);
}
return sb.ToString();

I did not benchmark this one, but i think it would be faster then StringBuilder.Insert because it does not move the rest of string many times, it just writes 4 chars. 我没有对此进行基准测试,但我认为它会比StringBuilder.Insert更快,因为它不会多次移动字符串的其余部分,它只会写入4个字符。 Also it would not reallocate the underlying string, because it's preallocated to 19 chars at the beginning. 此外,它不会重新分配底层字符串,因为它在开始时预先分配给19个字符。

Based on Carra's answer I made this little utility method: 根据Carra的回答,我做了一个小实用方法:

private static string ToDelimitedString(string input, int position, string delimiter)
{
  StringBuilder sb = new StringBuilder(input);

  int x = input.Length / position;

  while (--x > 0)
  {
    sb = sb.Insert(x * position, delimiter);
  }

  return sb.ToString();
}

You can use it like this: 你可以像这样使用它:

string result = ToDelimitedString("F4194E7CC775F003", 4, "-");

And a test case: 一个测试用例:

[Test]
public void ReturnsDelimitedString()
{
  string input = "F4194E7CC775F003";

  string actual = ToDelimitedString(input, 4, "-");

  Assert.AreEqual("F419-4E7C-C775-F003", actual);
}
 char[] chars = "F4194E7CC775F003".ToCharArray();
            var str = string.Format("{0}-{1}-{2}-{3}"
                                  , new string(chars.Take(4).ToArray())
                                  , new string(chars.Skip(4).Take(4).ToArray())
                                  , new string(chars.Skip(8).Take(4).ToArray())
                                  , new string(chars.Skip(12).Take(4).ToArray())  
                );

Simplest solution I can think of is 我能想到的最简单的解决方案是

        var text = "F4194E7CC775F003";
        var formattedText = string.Format(
            "{0}-{1}-{2}-{3}",
            text.Substring(0, 4),
            text.Substring(4, 4),
            text.Substring(8, 4),
            text.Substring(12, 4));

Only 9 years later, a minor variation from Carra's answer. 仅仅9年之后,卡拉的回答略有不同。 This yields about a 2.5x speed improvement based on my tests (change all "-" to '-'): 根据我的测试,这可以使速度提高2.5倍(将所有“ - ”更改为“ - ”):

        StringBuilder initial = new StringBuilder("F4194E7CC775F003");
        return initial.Insert(12, '-').Insert(8, '-').Insert(4, '-').ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM