Using String.Format To Dynamically Provide The Max Amount of Padding Needed

大憨熊 提交于 2019-12-11 13:44:58

问题


Hello I am trying to make my Console Application assignment more aesthically pleasing and by doing this I have decided to implement String.Format into my loops. We haven't been taught it but it is pretty easy to pick up. The main problem here is how do I parse a int into the String.Format so that it provides the max space needed.

This is the loop:

for (int index = 0; index < files.Length; index++)
{
    int maxNumericalSize = 2;
    int fileNumberSystem = index + 1;
    string result = string.Format("{0,maxNumericalSize}: {1,20} - {2,10} - {3}", fileNumberSystem, files[index].Name, files[index].Length, files[index].LastWriteTime );
    /* Console.WriteLine(fileNumberSystem + ". " + files[index].Name + " - " + files[index].Length + " - " + files[index].LastWriteTime); */
    Console.WriteLine(result);
}

As you can see MaxNumericalSize obviously throws an area as it is within speech marks so I am currently wondering how I could parse that into String.Format like that without the error.


回答1:


Try using string.PadLeft/string.PadRight to add additional spaces as follows

string.Format("{0}: {1,20} ..", fileNumberSystem.ToString().PadRight(maxNumericalSize), ...);

For PadRight it works like this

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

There's even an overload which let's you choose a character to fill in the space. You can find more on MSDN.



来源:https://stackoverflow.com/questions/27844702/using-string-format-to-dynamically-provide-the-max-amount-of-padding-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!