development

C #에서 문자열을 "곱셈"할 수 있습니까?

big-blog 2020. 7. 7. 07:15
반응형

C #에서 문자열을 "곱셈"할 수 있습니까?


예를 들어 문자열이 있다고 가정합니다.

string snip =  "</li></ul>";

정수 값에 따라 기본적으로 여러 번 쓰고 싶습니다.

string snip =  "</li></ul>";
int multiplier = 2;

// TODO: magic code to do this 
// snip * multiplier = "</li></ul></li></ul>";

편집 : 나는 이것을 구현하기 위해 쉽게 내 자신의 함수를 작성할 수 있다는 것을 알고있다. 나는 모르는 이상한 문자열 연산자가 있는지 궁금해했다.


.NET 4에서는 다음을 수행 할 수 있습니다.

String.Concat(Enumerable.Repeat("Hello", 4))

"문자열"이 단일 문자 인 경우이를 처리하기 위해 문자열 생성자가 오버로드됩니다.

int multipler = 10;
string TenAs = new string ('A', multipler);

불행히도 / 운 좋게도 문자열 클래스는 봉인되어 있으므로 상속 할 수 없으며 * 연산자를 오버로드 할 수 없습니다. 그래도 확장 방법을 만들 수 있습니다.

public static string Multiply(this string source, int multiplier)
{
   StringBuilder sb = new StringBuilder(multiplier * source.Length);
   for (int i = 0; i < multiplier; i++)
   {
       sb.Append(source);
   }

   return sb.ToString();
}

string s = "</li></ul>".Multiply(10);

나는 이것에 DrJokepu와 함께 있지만 어떤 이유로 든 내장 기능을 사용하여 속이기를 원한다면 다음과 같이 할 수 있습니다.

string snip = "</li></ul>";
int multiplier = 2;

string result = string.Join(snip, new string[multiplier + 1]);

또는 .NET 4를 사용하는 경우 :

string result = string.Concat(Enumerable.Repeat(snip, multiplier));

개인적으로 나는 귀찮게하지 않을 것입니다-사용자 정의 확장 방법이 훨씬 좋습니다.


완벽을 기하기 위해 여기에 또 다른 방법이 있습니다.

public static string Repeat(this string s, int count)
{
    var _s = new System.Text.StringBuilder().Insert(0, s, count).ToString();
    return _s;
}

나는 얼마 전에 Stack Overflow에서 그 것을 뽑았다 고 생각하기 때문에 내 생각이 아닙니다.


C # 3.0을 사용하는 방법은 물론 확장 방법이 될 수있는 방법을 작성해야합니다.

public static string Repeat(this string, int count) {
    /* StringBuilder etc */ }

그때:

string bar = "abc";
string foo = bar.Repeat(2);

*이 작업에 연산자를 실제로 사용하려면 조금 늦게 (그리고 단지 재미로) 다음과 같이하십시오.

public class StringWrap
{
    private string value;
    public StringWrap(string v)
    {
        this.value = v;
    }
    public static string operator *(StringWrap s, int n)
    {
        return s.value.Multiply(n); // DrJokepu extension
    }
}

그래서 :

var newStr = new StringWrap("TO_REPEAT") * 5;

만큼 당신이 그들을 위해 적절한 행동을 찾을 수 있습니다, 당신은 또한을 통해 다른 연산자를 처리 할 수있는, 그 참고 StringWrap클래스, 같은 \, ^, %등 ...

추신:

Multiply()@DrJokepu에 대한 확장 크레딧 모든 권리 보유 ;-)


이것은 훨씬 간결합니다.

new StringBuilder().Insert(0, "</li></ul>", count).ToString()

using System.Text;이 경우 네임 스페이스 를 가져와야합니다.


string Multiply(string input, int times)
{
     StringBuilder sb = new StringBuilder(input.length * times);
     for (int i = 0; i < times; i++)
     {
          sb.Append(input);
     }
     return sb.ToString();
}

If you have .Net 3.5 but not 4.0, you can use System.Linq's

String.Concat(Enumerable.Range(0, 4).Select(_ => "Hello").ToArray())

Since everyone is adding their own .NET4/Linq examples, I might as well add my own. (Basically, it DrJokepu's, reduced to a one-liner)

public static string Multiply(this string source, int multiplier) 
{ 
    return Enumerable.Range(1,multiplier)
             .Aggregate(new StringBuilder(multiplier*source.Length), 
                   (sb, n)=>sb.Append(source))
             .ToString();
}

Okay, here's my take on the matter:

public static class ExtensionMethods {
  public static string Multiply(this string text, int count)
  {
    return new string(Enumerable.Repeat(text, count)
      .SelectMany(s => s.ToCharArray()).ToArray());
  }
}

I'm being a bit silly of course, but when I need to have tabulation in code-generating classes, Enumerable.Repeat does it for me. And yeah, the StringBuilder version is fine, too.


Here's my take on this just for future reference:

    /// <summary>
    /// Repeats a System.String instance by the number of times specified;
    /// Each copy of thisString is separated by a separator
    /// </summary>
    /// <param name="thisString">
    /// The current string to be repeated
    /// </param>
    /// <param name="separator">
    /// Separator in between copies of thisString
    /// </param>
    /// <param name="repeatTimes">
    /// The number of times thisString is repeated</param>
    /// <returns>
    /// A repeated copy of thisString by repeatTimes times 
    /// and separated by the separator
    /// </returns>
    public static string Repeat(this string thisString, string separator, int repeatTimes) {
        return string.Join(separator, ParallelEnumerable.Repeat(thisString, repeatTimes));
    }

참고URL : https://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c

반응형