I have a fixed length string ABCDEFGHIJK, is there a way to convert this into AB-CDEFGHIJ-K using string format?
CodePudding user response:
var s = "ABCDEFGHIJK";
Console.WriteLine($"{s[..2]}-{s[2..10]}-{s[^1..]}");
CodePudding user response:
howabout
var newstring = String.format("{0}-{1}-{2}", s.Substring(0,2), s.Substring(3,7), s.Substring(10,1))
you could also use interpolation and the new range stuff
CodePudding user response:
var f = Regex.Replace("ABCDEFGHIJK", "^(..)(.*)(.)$", "$1-$2-$3");
...yeah, I know.
Also, dropping the {2}, etc. was inspired by Yuriy's answer here.
CodePudding user response:
I have a fixed length string ABCDEFGHIJK, is there a way to convert this into AB-CDEFGHIJ-K using string format?
Focusing on the "string format" part, we can implement IFormatProvider. This will format the string if it is EXACTLY eleven characters long, otherwise it just returns the same string back. Following the example, the "H" format stands for "hypenated":
private void button1_Click_2(object sender, EventArgs e)
{
string input = "ABCDEFGHIJK";
string output = String.Format(new MyStringFormat(), "Formatted: {0:H}", input);
Console.WriteLine(input);
Console.WriteLine(output);
}
public class MyStringFormat : IFormatProvider, ICustomFormatter
{
object IFormatProvider.GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg.GetType() != typeof(String))
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
}
}
string ufmt = format.ToUpper(CultureInfo.InvariantCulture);
if (ufmt != "H")
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
}
}
string result = arg.ToString();
if (result.Length != 11)
return result;
else
return result.Insert(2, "-").Insert(11, "-"); // see comment by Hans Passant!
}
private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
return arg.ToString();
else
return String.Empty;
}
}
CodePudding user response:
The Rube Goldberg way perhaps:
static void Main(string[] args)
{
string code = "ABCDEFGHIJK";
string mask = "##-########-#";
Console.WriteLine(code.Format(mask));
// AB-CDEFGHIJ-K
}
public static string Format(this string code, string mask, char token = '#')
{
StringBuilder sb = new StringBuilder(mask.Length);
int index = 0;
foreach (var item in mask)
{
if (item==token)
{
sb.Append(code[index ]);
}
else
{
sb.Append(item);
}
}
return sb.ToString();
}
Edit 1
replaced the space ' ' character placeholder with the pound sign '#' for better clarity.
