Fill string with blank boxes

Asked

Viewed 2,248 times

3

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

If you are less than 30, you should complete it with blanks, and if you have more, you should leave it with only 30.

I know you must have a way to do it like this:

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

But then it’s not working.

Any hint?

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);
  • I answered at the same time as you kkkkkkk

3

In the C#, there is the String.Padright function

Of MSDN

Returns a new character string of a specified length where the end of the current character 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)
  • I answered at the same time as you kkkkkkk

1

I was able to do it this way:

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

Padright completes spaces on the right, and the string on the side (with single quotes instead of doubles) must contain the character that completes the string

Browser other questions tagged

You are not signed in. Login or sign up in order to post.