C# 中的字符串相乘

发布于 2024-07-22 11:19:26 字数 540 浏览 5 评论 0原文

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

在 Python 中我可以这样做:

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

如何在 C# 中与 Python 中类似地乘以字符串?我可以轻松地在 for 循环中完成它,但这会变得乏味且缺乏表达力。

最终,我递归地编写控制台,缩进级别随着每次调用而递增。

parent
    child
    child
    child
        grandchild

最简单的方法是"\t" * indent

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

In Python I can do this:

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

How can I multiply strings in C# similarly to in Python? I could easily do it in a for loop but that gets tedious and non-expressive.

Ultimately I'm writing out to console recursively with an indented level being incremented with each call.

parent
    child
    child
    child
        grandchild

And it'd be easiest to just do "\t" * indent.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

扛刀软妹 2024-07-29 11:19:26

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

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

There is an extension method for it in this post.

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);
左耳近心 2024-07-29 11:19:26

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

new string('\t', i)

请参阅这篇文章了解更多信息。

If you just need a single character you can do:

new string('\t', i)

See this post for more info.

℡寂寞咖啡 2024-07-29 11:19:26

我是这样做的...

string value = new string(' ',5).Replace(" ","Apple");

Here's how I do it...

string value = new string(' ',5).Replace(" ","Apple");
幼儿园老大 2024-07-29 11:19:26

BCL 中没有内置任何东西来执行此操作,但使用一些 LINQ 就可以轻松完成该任务:

var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());

There's nothing built-in to the BCL to do this, but a bit of LINQ can accomplish the task easily enough:

var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());
大姐,你呐 2024-07-29 11:19:26
int indent = 5;
string s = new string('\t', indent);
int indent = 5;
string s = new string('\t', indent);
浅忆 2024-07-29 11:19:26

执行此操作的一种方法如下 - 但它并不那么好。

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

更新

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

 new String('x', 3)

One way of doing this is the following - but it's not that nice.

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

UPDATE

Ahhhh ... I remeber ... for chars ...

 new String('x', 3)
享受孤独 2024-07-29 11:19:26

使用 linq 聚合怎么样...

var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);

how about with a linq aggregate...

var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);
梦醒时光 2024-07-29 11:19:26

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

There is no such statement in C#; your best bet is probably your own MultiplyString() function.

霓裳挽歌倾城醉 2024-07-29 11:19:26

根据mmyers:

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

Per mmyers:

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();
}
忆梦 2024-07-29 11:19:26

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

string indentation = new String('\t', indent);

As long as it's only one character that you want to repeat, there is a String constructor that you can use:

string indentation = new String('\t', indent);
沉鱼一梦 2024-07-29 11:19:26

我不认为您可以使用运算符重载来扩展 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 循环中转储选项卡。

I don't think that you can extend System.String with an operator overload, but you could make a string wrapper class to do it.

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

Then call it like...

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

And get the value from...

helloTimesThree.Value;

Of course, the sane thing to do would be to have your function track and pass in the current depth and dump tabs out in a for loop based off of that.

℉服软 2024-07-29 11:19:26

如果你需要字符串 3 次就这样做

string x = "hello";

string combined = x + x + x;

if u need string 3 times just do

string x = "hello";

string combined = x + x + x;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文