그것은 할 수 있지만, 개인적으로 차라리 직접 문자열을 사용하십시오.
다음 코드는 아마 가장자리 경우를 포함하지만, 포인트 설명하지 않습니다
public sealed class SubstringFormatter : ICustomFormatter, IFormatProvider
{
private readonly static Regex regex = new Regex(@"(\d+),(\d+)", RegexOptions.Compiled);
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Match match = regex.Match(format);
if (!match.Success)
{
throw new FormatException("The format is not recognized: " + format);
}
if (arg == null)
{
return string.Empty;
}
int startIndex = int.Parse(match.Groups[1].Value);
int length = int.Parse(match.Groups[2].Value);
return arg.ToString().Substring(startIndex, length);
}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
}
가 호출하려면 다음
이
var formatter = new SubstringFormatter();
Console.WriteLine(string.Format(formatter, "{0:0,4}", "Hello"));
이것의 출력은 "지옥"이 될 것입니다
을 이것은 포맷이 아닙니다. 당신이 말한 것처럼 이것은 부분 문자열을 얻고 있습니다. –
그룹에 정규식을 사용할 수 있습니다 ... 형식 문자열의 일종입니다 –
형식 문자열은 대개 문자열을 "형식화"하는 데 사용됩니다. "단지"문자열의 특정 부분을 가져오고 싶습니까? 이 경우 몇 가지 방법이 있습니다. 당신이 뭘 하려는지는 분명하지 않습니다. 좀 더 구체적으로 말하십시오. –