2014-07-17 2 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")); 

이것의 출력은 "지옥"이 될 것입니다

관련 문제