3

If you take a look at the plastic in your wallet the 16 digit credit card number is broken into 4 groups of 4. Im trying to do the same thing,

Currently I have a string that has 16 digits but is formed as 1 single number. How can I add a " " after the 4th 8th & 12th number?

Any tips would be really helpful.

Thanks

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Diver Dan
  • 9,953
  • 22
  • 95
  • 166

6 Answers6

5
var number = 1234567890123456;
number.ToString( "0000-0000-0000-0000" );
Thomas
  • 63,911
  • 12
  • 95
  • 141
  • +1 Glad to see a simple solution to a simple problem. Some of the other answers are unnecessarily complex. At least so far, no one's suggested using a regex... – Cody Gray - on strike Apr 13 '11 at 04:59
  • @Cody - Sorry, but I have a regex in my answer. As Gabe commented, the OP may have a string, not a number, so that may be a valid approach. Also, the OP wants spaces, not dashes, but that's an easy fix. – Kobi Apr 13 '11 at 05:01
1

Try something similar to this answer, using a NumberFormatInfo:

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

Use as:

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

Or, if you're dealing with a string, you may choose can use a regex for a quick string manipulation. This will be easy to adapt to other characters:

string str = "7314787188619939";
str = Regex.Replace(str, "(?!^).{4}", " $0" ,RegexOptions.RightToLeft);
Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • The OP has the "number" as a string, not an integer. – Gabe Apr 13 '11 at 04:57
  • @Gabe - Already there `:)`. It's possible the OP just did a `.ToString` though, so it may have value. – Kobi Apr 13 '11 at 04:58
  • nice one Kobi, the regex is a nice way to do it :) – Diver Dan Apr 13 '11 at 05:07
  • string[] returnValue = Regex.Replace(forSplit, String.Format("(?!^).{{{0}}}", splitLength), " $0", RegexOptions.RightToLeft).Split(' '); allows passing 'splitLength' as a parameter – noonand Aug 19 '11 at 11:32
1
string number = "1234567890ABCDEF";
int counter = 0;
var result = number
    .GroupBy(_ => counter++ / 4)
    .Select(g => new String(g.ToArray()));
QrystaL
  • 4,886
  • 2
  • 24
  • 28
0

Or if working with MD5 hashes, you could use an implementation like so...

       public string exHashMd5(string data)
    {

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(data));
            byte[] result = md5.Hash;
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                str.Append(result[i].ToString("X2"));
            }

 /// The implementation like so. (Below) 

            NumberFormatInfo format = new NumberFormatInfo();
            format.NumberGroupSeparator = " ";
            format.NumberGroupSizes = new[] { 8 };
            format.NumberDecimalDigits = 0;
            string rstr = str.ToString();
            rstr = Regex.Replace(rstr, "(?!^).{8}", " $0", RegexOptions.RightToLeft);
            return rstr.ToString();

 /// At the end you get yourself a nice 4 way split.
 /// Test it out. have a go with chucking it into a 
 /// MessageBox.Show(exHashMd5("yourstring"));

    }

 /// Could even go one further and add
     string hashtext;
     string newline = Enviroment.Newline;
     hashtext = exHashMd5("yourtext");
/// Then you do a simple command.
    MessageBox.Show(hashtext + newline + hashtext); 
/// Nice four way again. complex but yet made simple.

To work out what you need it to do, use maths. seriously, its mathematical. divide the amount of characters, till you are able to get a sum that equals four. for example, 32 / 8 = 4. then this will give you the four way split you need. basic maths. basic. basic. basic.

MasterCassidy
  • 49
  • 1
  • 14
0

There are many answers. Given a string s=1234567890123456 the easiest might be to create a StringBuilder and append it. Untested code example below.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i += 4)
{
      sb.append(s.Substring(i, 4)); // Append these 4
      if (i != s.Length - 4)
          sb.append(" "); // append a space for all but the last group
}
Console.WriteLine(sb.ToString());
Kobi
  • 135,331
  • 41
  • 252
  • 292
Ben
  • 2,867
  • 2
  • 22
  • 32
  • 1
    If you do `i += 4` you won't need your `if` statement. Don't forget that last set of 4 chars, though. – Gabe Apr 13 '11 at 04:55
  • You're entirely correct, as I said it was untested - just giving a reference. – Ben Apr 13 '11 at 04:58
0

You may try something like this, an extension method

    public static IEnumerable<String> SplitToParts(this String forSplit, Int32 splitLength) 
    {   
        for (var i = 0; i < forSplit.Length; i += splitLength)
          yield return forSplit.Substring(i, Math.Min(splitLength, forSplit.Length - i));
    }
string s ="1234123412341234";

s.SplitToParts(4) should do the trick

Hope this works !

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82