Home > Back-end >  Add or remove char when string is small or big
Add or remove char when string is small or big

Time:11-10

string small = "12";
string big = "123456789";

I need to get exactly 8 characters (addition and removal respectively)
The result be like this:

small = "12      ";
big = "12345678";

CodePudding user response:

You can use String.PadRight:

string result = small.PadRight(8);

If a longer string should also be cut, use:

string result = text.Length > 8 ? text.Remove(8) : text.PadRight(8);

CodePudding user response:

If you want to obtain exactly 8 characters you can PadRight first (to have the text to be at least 8 chars long) and then take range (first 8 characters) to have exact 8 char long result:

var result = text.PadRight(8)[..8];
  • Related