string.pormat (padleft 또는 padright 아님)가있는 왼쪽 또는 오른쪽으로 패드 임의의 문자열이 있습니다.

StackOverflow https://stackoverflow.com/questions/541098

문제

string.format ()를 사용하여 임의 문자로 특정 문자열을 패드 할 수 있습니까?

Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");

returns 

->             hello<-
->hello             <-

나는 이제 공간이 임의의 캐릭터가되기를 원합니다. Padleft 또는 Padright로 할 수없는 이유는 다른 장소/시간에 형식 문자열을 구성 할 수 있기를 원하기 때문입니다. 그러면 실제로 형식이 실행되기 때문입니다.

--편집하다--
내 문제에 대한 기존 해결책이없는 것 같지 않다는 것을 알았습니다. 코딩의 제안 전에 생각하십시오)
-EDIT2-
더 복잡한 시나리오가 필요했기 때문에 코딩의 두 번째 제안 전에 생각하십시오

[TestMethod]
public void PaddedStringShouldPadLeft() {
    string result = string.Format(new PaddedStringFormatInfo(), "->{0:20:x} {1}<-", "Hello", "World");
    string expected = "->xxxxxxxxxxxxxxxHello World<-";
    Assert.AreEqual(result, expected);
}
[TestMethod]
public void PaddedStringShouldPadRight()
{
    string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-20:x}<-", "Hello", "World");
    string expected = "->Hello Worldxxxxxxxxxxxxxxx<-";
    Assert.AreEqual(result, expected);
}
[TestMethod]
public void ShouldPadLeftThenRight()
{
    string result = string.Format(new PaddedStringFormatInfo(), "->{0:10:L} {1:-10:R}<-", "Hello", "World");
    string expected = "->LLLLLHello WorldRRRRR<-";
    Assert.AreEqual(result, expected);
}
[TestMethod]
public void ShouldFormatRegular()
{
    string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-10}<-", "Hello", "World");
    string expected = string.Format("->{0} {1,-10}<-", "Hello", "World");
    Assert.AreEqual(expected, result);
}

코드가 게시물에 넣기에는 너무 많았 기 때문에 GIST로 GitHub로 옮겼습니다.
http://gist.github.com/533905#file_padded_string_format_info

사람들은 쉽게 분기 할 수 있습니다. :)

도움이 되었습니까?

해결책

다른 해결책이 있습니다.

구현하다 IFormatProvider a ICustomFormatter 그것은 string.format로 전달됩니다.

public class StringPadder : ICustomFormatter
{
  public string Format(string format, object arg,
       IFormatProvider formatProvider)
  {
     // do padding for string arguments
     // use default for others
  }
}

public class StringPadderFormatProvider : IFormatProvider
{
  public object GetFormat(Type formatType)
  { 
     if (formatType == typeof(ICustomFormatter))
        return new StringPadder();

     return null;
  }
  public static readonly IFormatProvider Default =
     new StringPadderFormatProvider();
}

그런 다음 다음과 같이 사용할 수 있습니다.

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

다른 팁

당신은 구조물로 끈을 캡슐화 할 수 있습니다.

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

그런 다음 이것을 사용하십시오.

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

결과:

"->xxxxxxxxxxxxxxxHello<-"

단순한:



    dim input as string = "SPQR"
    dim format as string =""
    dim result as string = ""

    'pad left:
    format = "{0,-8}"
    result = String.Format(format,input)
    'result = "SPQR    "

    'pad right
    format = "{0,8}"
    result = String.Format(format,input)
    'result = "    SPQR"


편집 : 나는 당신의 질문을 오해했는데, 나는 당신이 공간으로 패드하는 방법을 묻고 있다고 생각했습니다.

당신이 묻는 것은 string.Format 정렬 구성 요소; string.Format 항상 공백으로 패드. 참조 정렬 구성 요소 섹션 MSDN : 복합 형식.

반사판에 따르면, 이것은 내부에서 실행되는 코드입니다. StringBuilder.AppendFormat(IFormatProvider, string, object[]) 호출됩니다 string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

보시다시피, 공백은 흰색과 공백으로 채워 지도록 하드 코딩됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top