Home > OS >  String custom formatter .NET
String custom formatter .NET

Time:10-08

I have one trouble with custom formatting string.
I want to make smth like that:

var str = "SOME_ORIGINAL_FIELD_NAME";
var format1 = "XX_X_X";
var format2 = "X_XXX";

var strFormat1 = String.Format(str, format1); // SOMEORIGINAL_FIELD_NAME
var strFormat2 = String.Format(str, format2); // SOME_ORIGINALFIELDNAME

Does anybody know the right direction for searching? Maybe I should look at IFormatProvider and ICustomFormatter side.

CodePudding user response:

Sure, you just have to:

  • split the source string into its components,
  • use {i} placeholders instead of X, and
  • reverse the parameters to String.Format (format is first, data follows).

Example code (fiddle):

var components = "SOME_ORIGINAL_FIELD_NAME".Split('_');
var format1 = "{0}{1}_{2}_{3}";
var format2 = "{0}_{1}{2}{3}";

var strFormat1 = String.Format(format1, components); // SOMEORIGINAL_FIELD_NAME
var strFormat2 = String.Format(format2, components); // SOME_ORIGINALFIELDNAME

CodePudding user response:

Replace the X's in the format string with successive placeholders, and split the input string value into a string array, then apply string.Format():

public static string FormatSplitAndJoin(string input, string formatTemplate, string delimiter = "_", string placeholder = "X")
{
    // split "a_b_c" into ["a", "b", "c"]
    var parts = input.Split(delimiter);

    // turn "X_X_X" into "{0}_{1}_{2}"
    var index = 0;
    var formatString = Regex.Replace(formatTemplate, placeholder, m => string.Format("{{{0}}}", index  ));

    // validate input length
    if(index > parts.Length)
        throw new ArgumentException(string.Format("input string resulted in fewer arguments than expected, {0} placeholders found", index));

    // apply string.Format()
    return string.Format(formatString, parts);
}

Now you can do:

var str = "SOME_ORIGINAL_FIELD_NAME";
var format1 = "XX_X_X";
var format2 = "X_XXX";

var strFormat1 = FormatSplitAndJoin(str, format1); // SOMEORIGINAL_FIELD_NAME
var strFormat2 = FormatSplitAndJoin(str, format2); // SOME_ORIGINALFIELDNAME
  • Related