15

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?

Thanks.

DotnetSparrow
  • 27,428
  • 62
  • 183
  • 316
  • Could you describe the format more clearly and perhaps provide another example with a different number of digits - it looks like groups of 4 where possible, or does the first group need to be 2 digits? Also, check out this question which is very similar: http://stackoverflow.com/questions/5460962/using-string-format-for-a-credit-card-number – Steve Apr 01 '11 at 10:59
  • possible duplicate of [using string format for a credit card number](http://stackoverflow.com/questions/5460962/using-string-format-for-a-credit-card-number) – Steve Apr 01 '11 at 11:01

10 Answers10

13

By using regex:

    public static string FormatTest1(string num)
    {
        string formatPattern = @"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
        return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
    }

    // test
    string test = FormatTest1("731478718861993983");
    // test result: 73-1478-7188-6199-3983
HABJAN
  • 9,212
  • 3
  • 35
  • 59
9

If you're dealing with a long number, you can use a NumberFormatInfo to format it:

First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):

NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;        

Next, you can use it on your numbers:

long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);

After all, .Net has very good globalization support - you're better served using it!

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • The question was about a string, not a long, so it will need to be converted, as other answers spot. – Steve Apr 01 '11 at 10:57
  • @Steve - I know, I actually ignored that part on purpose! I've added [another answer for strings](http://stackoverflow.com/questions/5511846/formatting-string-in-mvc-c/5512110#5512110), and added this for number formatting. Either way, the OP should know how to convert the string, if that is needed, but that isn't the heart of the question. – Kobi Apr 01 '11 at 13:25
  • True, but my pedantic comment does have a point, if the string was longer it may not be possible to parse in to a long, so a "pure" string based answer that does not require the conversion would be worth considering, although since your answer was accepted I guess that is not an issue anyway. – Steve Apr 01 '11 at 13:27
2
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
Yngve B-Nilsen
  • 9,606
  • 2
  • 36
  • 50
1

LINQ-only one-liner:

var str = "731478718861993983";
var result = 
    new string(
        str.ToCharArray().
            Reverse(). // So that it will go over string right-to-left
            Select((c, i) => new { @char = c, group = i / 4}). // Keep group number
            Reverse(). // Restore original order
            GroupBy(t => t.group). // Now do the actual grouping
            Aggregate("", (s, grouping) => "-" + new string(
                grouping.
                    Select(gr => gr.@char).
                    ToArray())).
            ToArray()).
    Trim('-');

This can handle strings of arbitrary lenghs.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
1

Simple (and naive) extension method :

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("731478718861993983".InsertChar("-", 4));
    }
}

static class Ext
{
    public static string InsertChar(this string str, string c, int i)
    {
        for (int j = str.Length - i; j >= 0; j -= i)
        {
            str = str.Insert(j, c);
        }

        return str;
    }
}
mathieu
  • 30,974
  • 4
  • 64
  • 90
1

If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:

string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);

Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be @"\B\d{4}".

Kobi
  • 135,331
  • 41
  • 252
  • 292
0
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");
Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83
0

My first thought is:

String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");

(don't remember if index is zero-based, in which case you should use my values -1) but there is probably some easier way to do this...

0

Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.

string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));

Edit: amended code, since you said they were held as a string in your your original question

SeeSharp
  • 2,760
  • 16
  • 15
  • Ah, yeah, I missed that. Give me a few minutes and I'll revise. Well spotted. – SeeSharp Apr 01 '11 at 10:54
  • @kenny I can obviously `PadLeft()` up to a length of 22, but that'll only work for a maximum of two leading zeros. Back to the drawing board! – SeeSharp Apr 01 '11 at 11:15
0

If the position of "-" is always the same then you can try

string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-"); 
Gabriel
  • 1,435
  • 3
  • 17
  • 24