简体   繁体   中英

Formatting alphanumeric string

I have a string with 16 alphanumeric characters, eg F4194E7CC775F003. I'd like to format it as 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?

Thanks.

You can do it in one line without 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:

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. Also it would not reallocate the underlying string, because it's preallocated to 19 chars at the beginning.

Based on Carra's answer I made this little utility method:

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. This yields about a 2.5x speed improvement based on my tests (change all "-" to '-'):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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