C# 有没有一种方法可以使用格式化字符串来划分字符串?
我有一个字符串“123456”。这是一个数字,如果有帮助的话,我们也可以转换它。 我想使用一个格式字符串来输出“456”。可能吗?有点像子字符串(3,6),只有一个格式字符串C# 有没有一种方法可以使用格式化字符串来划分字符串?,c#,.net,C#,.net,我有一个字符串“123456”。这是一个数字,如果有帮助的话,我们也可以转换它。 我想使用一个格式字符串来输出“456”。可能吗?有点像子字符串(3,6),只有一个格式字符串 Ref:这是可以做到的,但就我个人而言,我宁愿直接使用子字符串 以下代码可能不包括边缘情况,但说明了这一点: public sealed class SubstringFormatter : ICustomFormatter, IFormatProvider { private readonly stati
Ref:这是可以做到的,但就我个人而言,我宁愿直接使用子字符串 以下代码可能不包括边缘情况,但说明了这一点:
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"));
输出为“地狱”这不是格式化。正如你所说,这是子字符串。你可以使用正则表达式,其中包含组。。。这是一种格式字符串格式字符串通常用于“格式化”字符串。您“只是”想要获取字符串的特定部分吗?在这种情况下,有几种方法。现在还不清楚你想做什么-请说得更具体一点。恐怕你得说得更清楚一点。456应该根据什么逻辑从原始字符串中“分区”?您想留下两个字符串(
“123”
和“456”
)吗?还是只提取456?是否存在任意数量的“分区”?更重要的是,使用String.Format
与使用Substring
相比,您的首选项是什么?