Fill string with blank boxes [duplicate]

3

I need to format a string so that it contains only 30 characters.

If you have less than 30, you should fill in the blanks, and if you have more, you should leave it with only 30.

I know you should have a way to do + - like this:

string.Format("{0:                              }, item.nome");

But this is not working.

Any tips?

    
asked by anonymous 08.03.2017 / 20:04

3 answers

3

Use PadRight to complete with spaces if the string is less than 30 characters (or 30 because nothing happens there) and Substring to cut it otherwise.

item.nome.Length <= 30 ? item.nome.PadRight(30, ' ') : item.nome.Substring(0, 30);
    
08.03.2017 / 20:06
3

In C# , there is the function String.PadRight

  

From the MSDN
< br>   Returns a new string of a specified length where the end of the current string will be filled with spaces or with a specified Unicode character.

So, to complete with spaces, in your case you can use:

item.nome.PadRight(30)
    
08.03.2017 / 20:09
1

I was able to do the following:

item.nome.PadRight(30, ' ');

PadRight completes spaces to the right, and the adjacent string (with single quotes instead of double quotes) must contain the character that will complete the string

    
08.03.2017 / 20:46