gpt4 book ai didi

c# - Python 的 print "0"*5 在 C# 中等效

转载 作者:太空狗 更新时间:2023-10-29 22:11:10 26 4
gpt4 key购买 nike

当我需要打印“00000”时,我可以在python中使用“0”*5。 C# 中是否有没有循环的等价物?

最佳答案

根据您的示例,我认为您将使用这些字符串来帮助零填充一些数字。如果是这样的话,使用 String.PadLeft() 会更容易。方法来做你的填充。您也可以在 python 中使用类似的函数,rjust() .

例如,

var str = "5";
var padded = str.PadLeft(8, '0'); // pad the string to 8 characters, filling in '0's
// padded = "00000005"

否则,如果您需要重复的字符串序列,则需要使用 String.Concat()方法结合 Enumerable.Repeat()方法。使用字符串构造函数只允许重复单个字符。

例如,

var chr = '0';
var repeatedChr = new String(chr, 8);
// repeatedChr = "00000000";
var str = "ha";
// var repeatedStr = new String(str, 5); // error, no equivalent
var repeated = String.Concat(Enumerable.Repeat(str, 5));
// repeated = "hahahahaha"

关于c# - Python 的 print "0"*5 在 C# 中等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7452558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com