임의의 공유로 string.format (padleft 또는 padright 아님)으로 왼쪽 또는 오른쪽 채우기
String.Format ()을 사용하여 어디에서 임의의 문자로 채울 수 있습니까?
Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");
returns
-> hello<-
->hello <-
이제 공백이 임의의 문자가되기를 원합니다. padLeft 또는 padRight로 할 수없는 이유는 다른 장소 / 시간에 형식을 사용할 수 있도록 구성 할 수 있기 때문에 형식화가 실제로 실행되기 때문입니다.
--EDIT--
내 문제에, 대한 기존 솔루션이없는을 구석으로 같음 나는 이것을 생각해
냈다 ( 코딩하기 전에 생각 제안의 이후 ) --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);
}
코드가 게시물에 넣기에는 너무 많았 기 때문에 요점으로 github로 옮겼습니다.
http://gist.github.com/533905#file_padded_string_format_info
사람들이 쉽게 분기 할 수 있습니다. :)
또 다른 해결책이 있습니다.
및 String.format 전달 될를에 IFormatProvider
반환하도록 구현 합니다 ICustomFormatter
.
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");
IFormattable을 구현할 수 있습니다.
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<-"
편집 : 나는 당신의 질문을 오해했습니다. 나는 당신이 공백으로 채우는 방법을 생각했습니다.
당신이 요청하는 정렬 string.Format
구성 요소를 사용하여 가능하지 않습니다 . string.Format
항상 공백으로 채입니다. MSDN : Composite Formatting 의 Alignment Component 섹션을 참조하십시오 .
반사판에 따르면,이 안에 실행 코드 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);
}
보시다시피 공백은 공백으로 채워지도록 하드 코딩되어 있습니다.
단순한:
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"
'ProgramingTip' 카테고리의 다른 글
ssl없이 npm 설치 (0) | 2020.12.28 |
---|---|
Bash if 문에서 정규식 일치 (0) | 2020.12.28 |
자이 썬에서 안드로이드 앱 프로그래밍 (0) | 2020.12.27 |
Slack에서 하이퍼 링크 만들기 (0) | 2020.12.27 |
다중 블루투스 연결 (0) | 2020.12.27 |