Master Yoda
Master Yoda

Reputation: 4422

Convert card numbers to XXXX-XXXX-XXXX-0000 Format

I have a 16 character string that comes through something like this:

1234567891234567

I need to be able to format the string as it would appear in a system i.e

XXXX-XXXX-XXXX-4567

NOTE that the 4567 digits shown above relate to the last four digits of the card number.

This question helps format the string to something like 1234-5678-9123-4567

But it does not help with the format required above.

While looking for answers I also came across the following solution:

    string[] subStrings = Enumerable.Range(0, 4).Select(n => cardNumber.Substring(n * 4, 4)).ToArray();
    string result = String.Format("{0}-{1}-{2}-{3}", subStrings);

but again this will only output the string as something like 1234-5678-9123-4567

I seem to have reached part of the solution, but cant format the rest.

Upvotes: 2

Views: 99888

Answers (4)

Cihan Uygun
Cihan Uygun

Reputation: 2138

You can create a char[] from your string then you can group your char[] into chunks of char[4] then you can simply join your char[4] into dashed string. Can you try the code below;

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string source = "1234567891234567";
        int chunkSize = 4;

        List<string> chunks = (from i in source.ToCharArray().Select((value, index) => new { Value = value, Index = index })
                                  group i.Value by i.Index / chunkSize into g
                                  select g).Select(x => string.Join("",x)).ToList();


        Console.WriteLine(string.Join("-",chunks));
        Console.WriteLine("XXXX-XXXX-XXXX-"+chunks.Last());
        Console.WriteLine(chunks.First()+"-XXXX-XXXX-"+chunks.Last());
    }
}

Hope this helps. PS: You can pick any nth index of your chunk to mask or show.

Upvotes: 0

mikeyq6
mikeyq6

Reputation: 1148

Keeping your original code, you could just do:

string[] subStrings = Enumerable.Range(0, 4).Select(n => cardNumber.Substring(n * 4, 4)).ToArray();
string result = String.Format("XXXX-XXXX-XXXX-{0}", subStrings[3]);

Upvotes: 1

Habib
Habib

Reputation: 223422

If your string credit card number will always be 16 digits, then you can do something like:

string str = "1234567891234567";    
string output = "XXXX-XXXX-XXXX-" + str.Substring(str.Length - 4);

Upvotes: 8

Daniel A. White
Daniel A. White

Reputation: 191058

You could reassign the array values.

subStrings[0] = subStrings[1] = subStrings[2] = "XXXX"

Upvotes: 2

Related Questions