6

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

在 Python 中,我可以这样做:

>>> i = 3
>>> 'hello' * i
'hellohellohello'

如何在 C# 中将字符串相乘,就像在 Python 中一样? 我可以很容易地在 for 循环中做到这一点,但这会变得乏味且缺乏表现力。

最终,我正在递归地写出控制台,每次调用都会增加一个缩进级别。

parent
    child
    child
    child
        grandchild

这样做是最容易的"\t" * indent

4

12 回答 12

19

在这篇文章中有一个扩展方法。

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);
于 2009-06-05T20:24:47.987 回答
14

如果你只需要一个字符,你可以这样做:

new string('\t', i)

有关更多信息,请参阅此帖子

于 2009-06-05T20:24:53.917 回答
12

这是我的做法...

string value = new string(' ',5).Replace(" ","Apple");
于 2009-06-05T20:32:42.497 回答
11

BCL 没有任何内置功能可以做到这一点,但是一点 LINQ 可以很容易地完成任务:

var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());
于 2009-06-05T20:25:06.007 回答
1
int indent = 5;
string s = new string('\t', indent);
于 2009-06-05T20:27:42.193 回答
1

这样做的一种方法是以下 - 但它不是那么好。

 String.Join(String.Empty, Enumerable.Repeat("hello", 3).ToArray())

更新

啊……我记得……对于字符……

 new String('x', 3)
于 2009-06-05T20:28:24.377 回答
1

使用 linq 聚合如何...

var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);
于 2009-06-05T20:29:19.460 回答
0

C#中没有这样的语句;您最好的选择可能是您自己的 MultiplyString() 函数。

于 2009-06-05T20:22:28.570 回答
0

每毫米:

public static string times(this string str, int count)
{
  StringBuilder sb = new StringBuilder();
  for(int i=0; i<count; i++) 
  {
    sb.Append(str);
  }
  return sb.ToString();
}
于 2009-06-05T20:27:17.373 回答
0

只要您只想重复一个字符,就可以使用 String 构造函数:

string indentation = new String('\t', indent);
于 2009-06-05T20:29:00.397 回答
0

我不认为您可以使用运算符重载扩展 System.String,但您可以创建一个字符串包装类来做到这一点。

public class StringWrapper
{
    public string Value { get; set; }

    public StringWrapper()
    {
        this.Value = string.Empty;
    }

    public StringWrapper(string value)
    {
        this.Value = value;
    }

    public static StringWrapper operator *(StringWrapper wrapper,
                                           int timesToRepeat)
    {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < timesToRepeat; i++)
        {
            builder.Append(wrapper.Value);
        }

        return new StringWrapper(builder.ToString());
    }
}

然后称它为...

var helloTimesThree = new StringWrapper("hello") * 3;

并从...中获取价值

helloTimesThree.Value;

当然,明智的做法是让你的函数跟踪并传入当前深度,并以此为基础在 for 循环中转储选项卡。

于 2009-06-05T20:40:03.557 回答
-1

如果你需要字符串 3 次就行

string x = "hello";

string combined = x + x + x;
于 2009-06-05T20:42:45.720 回答