C#字符串格式标志或修改为小写参数 [英] C# string format flag or modifier to lowercase param
问题描述
是否可以指定某种标志或改性剂以字符串格式参数来定制它,有点像数字格式化标志?的要我要
Is it possible to specify some kind of flag or modifier to a string format param to customize it, something like the number formating flags?
例
String.Format("Hi {0:touppercase}, you have {1} {2:tolowercase}.", "John", 6, "Apples");
通缉输出:嗨约翰,你有6个苹果
Wanted output: Hi JOHN, you have 6 apples.
PS:是的,我知道我可以改变参数的情况下使用它的字符串格式之前,但我不希望这样。
PS: Yes I know that I can change the case of the param before using it on the string format but I don't want this.
推荐答案
有只有填充和排成一条直线格式化......所以,简单的方法就是像你说的,使用约翰.ToUpper()
或约翰.ToLower()
。
There's only padding and allignment formating... So the easy way is like you said, use "John".ToUpper()
or "John".ToLower()
.
另一种解决方案是创建一个自定义的IFormatProvider
,提供你想要的字符串格式。
Another solution could be create a custom IFormatProvider
, to provide the string format you want.
这是如何看的的IFormatProvider
,以及呼叫的String.Format
This is how will look the IFormatProvider
and the string.Format call.
public class CustomStringFormat : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
string result = arg.ToString();
switch (format.ToUpper())
{
case "U": return result.ToUpper();
case "L": return result.ToLower();
//more custom formats
default: return result;
}
}
}
和通话的样子
String.Format(new CustomStringFormat(), "Hi {0:U}", "John");
这篇关于C#字符串格式标志或修改为小写参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!