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

标签 c# printing

当我需要打印“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/

相关文章:

java - 访问 Thymeleaf 中的 HashMap 键

c# - Web.config中调用连接字符串出现非法字符异常

c# - 从类中调用随机方法

android - 通过蓝牙打印机打印时获取 java.io.IOException : read failed, 套接字可能已关闭或超时,请读取 ret: -1

java - 输入2个整数数组并打印交替元素

Java 打印模板

c# - 正则表达式在 .NET 中不起作用

c# - 如何在 HQL 中使用 DATEPART 从 DATETIME 获取 YEAR

c# - .Net Core MVC 自定义登录屏幕

pdf - 打印通过 Flutter/Dart 中的网络服务下载的 pdf