Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim and pad in one string method

Tags:

c#

.net

I have a method that accept one string and it has to get a string with exactly 5 chars.
There is a possibility the user will insert string with more then 5 chars - in that case I want to trim left.
There is a possibility the user will insert string with more less then 5 chars - in that case I want to pad left.

I know I can do it with if/else condition but I wonder maybe string class has something helpfull to deal with such cases in one command.

What do you think?

like image 429
Naor Avatar asked May 29 '11 22:05

Naor


People also ask

What a trim() in string does?

The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".

What is string padding?

The Padding String function returns a padding string of the specified length and characters. Padding strings are used in alignment functions. Parameter: number. The total length to make the padding string. This can come from a source node, the result of another function, or a value you specify.

Does trim change the string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.

What is PadRight?

PadRight(Int32, Char) Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.


1 Answers

Try padding to 5 chars and then trimming to 5 chars. It doesn't matter that the padding may make it too long because the trimming will fix that! :-)

like image 66
MRAB Avatar answered Oct 12 '22 00:10

MRAB