0
public static string ToIbanFormat(this string value)
        {
            if (value.Length > 16)
            {
                string iban = value.Substring(0, 4) + " " + 
                              value.Substring(4, 4) + " " + 
                              value.Substring(8, 4) + " " + 
                              value.Substring(12, 4) + " " +
                              value.Substring(16);

                return iban;
            }

            return value;
        }

can I somehow do it dynamically if there is more characters that I can use spaces also after each 4 char.

For example my code will not work for: GR16 0110 1250 0000 0001 2300 695

and I do n't want to add another if. Can I do this dynamically to check the length and then substring it?

mbrc
  • 3,523
  • 13
  • 40
  • 64

4 Answers4

3

You can replace every 4th character with that character plus a space:

return value
    .Select((x, i) => (i + 1) % 4 == 0 ? x + " " : x.ToString())
    .Aggregate((x, y) => x + y);
mihai
  • 4,592
  • 3
  • 29
  • 42
  • The good thing about this is that you can change `(i + 1) % 4 == 0` into `(i + 1) % 4 == 0 && x != ' '` if you want to not insert the space if `x` is already a space, `' '`. The question is unclear, but maybe the asker wanted that. – Jeppe Stig Nielsen Nov 26 '14 at 11:39
  • (Edited!) With `Concat` your answer becomes `return string.Concat(value.Select((x, i) => (i + 1) % 4 == 0 ? x + " " : x.ToString()));`. – Jeppe Stig Nielsen Nov 26 '14 at 11:42
3

Regex.Replace(value, ".{4}", "$0 ").Trim() should do the trick.

Anonymous
  • 9,366
  • 22
  • 83
  • 133
1

This works:

var text = "GR1601101250000000012300695";

var result = String.Join(" ",
    text
        .ToCharArray()
        .Buffer(4)
        .Select(x => new string(x.ToArray())));

But Bufferrequires that you NuGet "Ix-Main" from the Microsoft Reactive Framework Team.

Personally I like the RegEx approach, but I think this is more readable and hence more maintainable.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1
String str = "GR1601101250000000012300695";
StringBuilder result=new StringBuilder();
for(int i=0;i<str.Length;i++)
{
  if ((i+1) % 4 == 0)
    result.Append(str[i] + " ");
  else
    result.Append(str[i]);
}

result = GR16 0110 1250 0000 0001 2300 695

Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67