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?
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.
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})")
#means numeral. You have aUin the middle of the string, which is not a numeral. Additionally, when passing in a string tostring.Format, nothing will happen with the string - it will be returned as is.