我可以“乘以”一个字符串(在 C# 中)吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/532892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:06:05  来源:igfitidea点击:

Can I "multiply" a string (in C#)?

c#stringextension-methods

提问by inspite

Suppose I have a string, for example,

假设我有一个字符串,例如,

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

I want to basically write it multiple times, depending on some integer value.

我想基本上写多次,这取决于一些整数值。

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

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

EDIT: I know I can easily write my own function to implement this, I was just wondering if there was some weird string operator that I didn't know about

编辑:我知道我可以轻松编写自己的函数来实现这一点,我只是想知道是否有一些我不知道的奇怪的字符串运算符

采纳答案by Will Dean

In .NET 4 you can do this:

在 .NET 4 中,你可以这样做:

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

回答by Tamas Czinege

Unfortunately / fortunately, the string class is sealed so you can't inherit from it and overload the * operator. You can create an extension method though:

不幸/幸运的是,字符串类是密封的,因此您不能从它继承并重载 * 运算符。你可以创建一个扩展方法:

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);

回答by Marc Gravell

You'd have to write a method - of course, with C# 3.0 it could be an extension method:

您必须编写一个方法 - 当然,对于 C# 3.0,它可以是一个扩展方法:

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

then:

然后:

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

回答by Chris Ballance

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();
}

回答by LukeH

I'm with DrJokepu on this one, but if for some reason you did want to cheat using built-in functionality then you could do something like this:

我和 DrJokepu 一起讨论这个问题,但如果由于某种原因你确实想使用内置功能作弊,那么你可以做这样的事情:

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

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

Or, if you're using .NET 4:

或者,如果您使用的是 .NET 4:

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

Personally I wouldn't bother though - a custom extension method is much nicer.

就我个人而言,我不会打扰 - 自定义扩展方法要好得多。

回答by Dmitri Nesteruk

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.

我当然有点傻,但是当我需要在代码生成类中进行制表时, Enumerable.Repeat 会为我做这件事。是的,StringBuilder 版本也很好。

回答by James Curran

Note that if your "string" is only a single character, there is an overload of the string constructor to handle it:

请注意,如果您的“字符串”只是一个字符,则字符串构造函数的重载来处理它:

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

回答by user51710

Just for the sake of completeness - here is another way of doing this:

只是为了完整起见 - 这是另一种方法:

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

I think I pulled that one from Stack Overflow some time ago, so it is not my idea.

我想我前段时间从 Stack Overflow 中提取了那个,所以这不是我的主意。

回答by Jronny

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));
    }

回答by Frank Schwieterman

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

如果你有 .Net 3.5 但没有 4.0,你可以使用 System.Linq's

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