항목 깊이에 따라 문자열 앞에 일정한 수의 들여 쓰기를 삽입하려고하는데 X 번 반복 된 문자열을 반환하는 방법이 있는지 궁금합니다. 예:
string indent = "---";
Console.WriteLine(indent.Repeat(0)); //would print nothing.
Console.WriteLine(indent.Repeat(1)); //would print "---".
Console.WriteLine(indent.Repeat(2)); //would print "------".
Console.WriteLine(indent.Repeat(3)); //would print "---------".
답변
동일한 문자 만 반복하려는 경우 문자 를 허용하는 문자열 생성자 와 반복 횟수를 사용할 수 new String(char c, int count)
있습니다.
예를 들어 대시를 다섯 번 반복하려면
string result = new String('-', 5);
Output: -----
답변
.NET 4.0을 사용 string.Concat
하는 경우와 함께 사용할 수 있습니다 Enumerable.Repeat
.
int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));
그렇지 않으면 나는 Adam ‘s answer 와 같은 것을 가지고 갈 것입니다 .
내가 Andrey의 답변을 사용 하지 말라고 일반적으로 조언 하지 않는 이유 는 단순히 전화 가 Adam이 제안한 접근 방식으로 피할 수없는 불필요한 오버 헤드를 유발하기 때문입니다 . 즉, 적어도 .NET 4.0을 요구하지 않고 작동합니다. 그리고 빠르고 쉽습니다 (효율성이 그다지 중요하지 않으면 당신을 죽이지 않을 것입니다).ToArray()
StringBuilder
답변
public static class StringExtensions
{
public static string Repeat(this string input, int count)
{
if (!string.IsNullOrEmpty(input))
{
StringBuilder builder = new StringBuilder(input.Length * count);
for(int i = 0; i < count; i++) builder.Append(input);
return builder.ToString();
}
return string.Empty;
}
}
답변
문자열에 가장 성능이 뛰어난 솔루션
string result = new StringBuilder().Insert(0, "---", 5).ToString();
답변
많은 시나리오에서 아마도 가장 적은 해결책 일 것입니다.
public static class StringExtensions
{
public static string Repeat(this string s, int n)
=> new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}
그러면 사용법은 다음과 같습니다.
text = "Hello World! ".Repeat(5);
이것은 다른 답변 (특히 @ c0rd)을 기반으로합니다. 단순성뿐만 아니라 다음과 같은 기능을 가지고 있습니다.
- 문자가 아닌 모든 길이의 문자열 반복 (OP에서 요청한대로).
StringBuilder
스토리지 사전 할당을 효율적으로 사용 합니다.
답변
원하는 문자열에 단일 문자 만 포함 된 경우 String.PadLeft를 사용하십시오 .
public static string Indent(int count, char pad)
{
return String.Empty.PadLeft(count, pad);
}
여기에 크레딧
답변
문자열을 반복하고 (단일 문자가 아닌 경우) 다음과 같이 결과를 연결할 수 있습니다.
String.Concat(Enumerable.Repeat("---", 5))
