C# 中的字符串相乘
可能的重复:
我可以“乘”一个字符串(在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
这篇文章中有一个扩展方法。
There is an extension method for it in this post.
如果您只需要一个字符,您可以这样做:
请参阅这篇文章了解更多信息。
If you just need a single character you can do:
See this post for more info.
我是这样做的...
Here's how I do it...
BCL 中没有内置任何东西来执行此操作,但使用一些 LINQ 就可以轻松完成该任务:
There's nothing built-in to the BCL to do this, but a bit of LINQ can accomplish the task easily enough:
执行此操作的一种方法如下 - 但它并不那么好。
更新
啊啊...我记得...对于字符...
One way of doing this is the following - but it's not that nice.
UPDATE
Ahhhh ... I remeber ... for chars ...
使用 linq 聚合怎么样...
how about with a linq aggregate...
C#中没有这样的语句; 你最好的选择可能是你自己的 MultiplyString() 函数。
There is no such statement in C#; your best bet is probably your own MultiplyString() function.
根据mmyers:
Per mmyers:
只要您只想重复一个字符,就可以使用一个 String 构造函数:
As long as it's only one character that you want to repeat, there is a String constructor that you can use:
我不认为您可以使用运算符重载来扩展 System.String,但您可以创建一个字符串包装类来执行此操作。
然后像这样调用它...
并从中获取值...
当然,明智的做法是让您的函数跟踪并传入当前深度,并基于此在 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.
Then call it like...
And get the value from...
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.
如果你需要字符串 3 次就这样做
if u need string 3 times just do