One-way cropping and overlay

I have a method that takes a single line, and it should get a line with exactly 5 characters.
There is a possibility that the user inserts a line with more than 5 characters - in this case I want to trim to the left.
There is a possibility that the user will enter a string with more than 5 characters - in this case I want the panel on the left.

I know that I can do this with the if / else condition, but I'm wondering, maybe the string class has something useful to solve such cases in one command.

What do you think?

+5
source share
6 answers

5 , 5 . , , !: -)

+6

, , ...

string hi = "hello world"; //or try = "hi";
hi = hi.PadLeft(5, '0'); 
hi = hi.Substring(hi.Length - 5);
Console.WriteLine(hi);
+4

These are branches, of course, but to be honest, I think itโ€™s neat enough:

var maxLength = 5;
var paddingChar = 'x';

input = input.Length > maxLength ?
    input.Remove(0, input.Length - maxLength) :
    input.PadLeft(maxLength, paddingChar);
+2
source

You can create a PadRight extension (or PadLeft), for example:

public static string PadRight2(this string value, int exactWidth)
{
    return value.PadRight(exactWidth).Substring(0, exactWidth);
}
0
source

Assuming you want to put the character "A", how about:

("AAAAA" + st).Substring(st.Length)
// Note: padded string has length (st.Length + 5)  
// ... so substring offset is ((st.Length+5)-5) = st.Length

(left) or:

(st + "AAAAA").Substring(0,5)

(on right)?

-1
source

try the following:

string str = "abcdefghjxd";
 string split = str.Substring(0, 5);
-6
source

All Articles