本文介绍了变量String.Format长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  

解决方案

格式字符串也只是字符串 - 您可以分别定义格式:

  int n = 3; 
string format = string.Format({{0,{0}}},n);
//更可读:string format ={0,+ n +};
var output = string.Format(format,str);

编辑:

看起来像你想要的也可以通过:

  var str =ABC; 
string output = str.PadLeft(7);


I have the following code:

var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);

This should output the string

"    ABC"

How should I change the line above?

解决方案

Format strings are just strings too - you can define the format separately:

int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);

Edit:

After your update it looks like what you want can also be achieved by PadLeft():

var str = "ABC";
string output = str.PadLeft(7);

这篇关于变量String.Format长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:55