2014-07-17 60 views
0

我有一个字符串“123456”。这是一个数字,如果有帮助,我们也可以将其转换。 我想使用格式字符串来获取“456”。那可能吗?有些子字符串(3,6)只有一个格式字符串。有没有办法使用格式字符串来分割字符串?

编号:http://msdn.microsoft.com/en-us/library/vstudio/0c899ak8(v=vs.100).aspx

+0

这不是格式化。这就像你说的那样得到了子串。 –

+1

你可以在其中使用正则表达式...这是一种格式字符串 –

+0

格式字符串通常用于“格式化”一个字符串。你“只是”想要得到字符串的特定部分吗?在这种情况下有几种方法。这是不是很清楚你想做什么 - 请更具体一点。 –

回答

1

这是可以做到的,但我个人宁愿直接使用字符串。

下面的代码可能不会覆盖边缘情况,但说明了这一点:

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")); 

的输出,这将是“地狱”

相关问题