0

I found that with long.Parse, ToString can take argument and I can format it to desired string, for example.

Input:    
Console.WriteLine(long.Parse("123").ToString("#-#-#"));

Output:
1-2-3

I wanted to do something similar with string, lets say I wanna parse string to format ####-###-####. Is there any way to do it without regex with one liner like example above?

EDIT

Ok, so I may be misunderstood, I didn't want to parse numbers, but string instead. I can do in python like:

'{}-{}-{}'.format(*'abc') and I will receive a-b-c. In C# it seems to work only with numbers.

Thou
  • 1,055
  • 3
  • 11
  • 16

1 Answers1

0

Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Console.WriteLine("Hello, world!");

            Console.WriteLine("helloWorld".ToPhoneNumber("###-###-####"));
        }
    }

    public static class AdvancedFormatString
    {    
        public static string ToPhoneNumber(this string strArg, string outputformat)
        {
            if (outputformat == null)
                return strArg;

            var sb = new StringBuilder();
            var i = 0;

            foreach (var c in outputformat)
            {
                if (c == '#')
                {
                    if (i < strArg.Length)
                    {
                        sb.Append(strArg[i]);
                    }
                    i++;
                }
                else
                {
                    sb.Append(c);
                }
            }

            return sb.ToString();
        }
    }
}
Jophy job
  • 1,924
  • 2
  • 20
  • 38