0

Well,

I just can't format the following string:

string oldFormat = "949123U0456789";
oldFormat = string.Format(@"{0: ###.###-##-###.###}",oldFormat);

the result should be: 949.123-U0-456.789

Does anyone have a better way to format this string?

3
  • 3
    # means numeral. You have a U in the middle of the string, which is not a numeral. Additionally, when passing in a string to string.Format, nothing will happen with the string - it will be returned as is. Commented Aug 16, 2012 at 14:04
  • 1
    possible duplicate of Format string with dashes Commented Aug 16, 2012 at 14:09
  • I found [this][1] here on stackoverflow. It uses LINQ. [1]: stackoverflow.com/questions/2287023/… Commented Aug 16, 2012 at 14:19

3 Answers 3

8

You can use Insert:

"949123U0456789".Insert(11, ".").Insert(8, "-").Insert(6, "-").Insert(3, ".")

Note that I am inserting from the end, to avoid the addition of the inserted string from affecting the index.

The format string you have used is meant for numeric types - a string is not a numeric types (and when passing in a string to string.Format, it will simply be returned, as it already is a string).

There are other approaches, as can be seen in Format string with dashes:

Using regex:

Regex.Replace("949123U0456789",
              @"^(.{3})(.{3})(.{2})(.{3})(.{3})$",
              "$1.$2-$3-$4.$5");

Or with Substring.

Sign up to request clarification or add additional context in comments.

1 Comment

Very Clever! People should point his attention in the order. Is very important follow the order, from back to front. Great and simple!
1

Regex can solve the problem of formatting when there is a mix of letters and numbers.

        using System.Text.RegularExpressions;

        string pattern = @"([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{2})([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})"
        string oldFormat = "949123U0456789";
        string newFormat = Regex.Replace(oldFormat, pattern, 
                    "$1.$2-$3-$4.$5");

I love regular expressions :D, they have the added benefit of allowing you to check the syntax of the code, if it has to follow a certain convention (i.e. perform validation).

In order to perform validation, you can use:

        Regex.IsMatch(oldFormat, 
                    @"([a-z0-9A-Z]{3})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{2})([a-z0-9A-Z]{3})
                    ([a-z0-9A-Z]{3})")

Comments

0
string s="949123U0456789";

Regex r=new Regex(@"(\w{3})(\w{3})(\w{2})(\w{3})(\w{3})");
Console.WriteLine(r.Replace(s,"$1.$2-$3-$4.$5"));

Comments

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.