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.

2
  • 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: stackoverflow.com/questions/5460962/… Commented Apr 1, 2011 at 10:59
  • possible duplicate of using string format for a credit card number Commented Apr 1, 2011 at 11:01

10 Answers 10

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
Sign up to request clarification or add additional context in comments.

4 Comments

So much better... I'm retiring my answer.
If you have 1 problem and solve it by a regex, you now have 2 problems :)
@mathieu - If you have a problem and apply aphorisms and dogmatic thinking, well, I'm not sure what you have then.
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!

3 Comments

The question was about a string, not a long, so it will need to be converted, as other answers spot.
@Steve - I know, I actually ignored that part on purpose! I've added another answer for strings, 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.
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.
2
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));

Comments

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.

2 Comments

one liner....we have a different definition. just because you can put it on a line....
@kenny: Purely as an exercise.
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;
    }
}

Comments

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}".

Comments

0
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");

Comments

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...

Comments

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

Comments

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

2 Comments

Ah, yeah, I missed that. Give me a few minutes and I'll revise. Well spotted.
@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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.