简体   繁体   中英

How to use variable inside String.Format

I want to use String.Format inside the loop, but it does not allowing me to define a variable i inside the String.Format . Here is my code

StringBuilder Sb;
for(i=0 ;i<=myObj.length;i++)
{
    Sb=Sb.Append(String.Format("{i,5}",myObj[i].Tostring()));
}

To use it in the Format method, you use numbers corresponding to the indexes of the params array.

Also, don't reassign Sb , just call Append or AppendFormat :

Sb.Append(String.Format("{0,5}", myObj[i].ToString()));
//or
Sb.AppendFormat("{0,5}", myObj[i].ToString());

If you're fortunate enough to be on the latest and greatest C# version, you can skip Format and do it with the new string interpolation syntax:

Sp.Append($"{myObj[i],5}");

Or since all you're doing is padding, then you can also do:

Sb.Append(myObj[i].ToString().PadLeft(5));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM