开发者

trim and pad in one string method

开发者 https://www.devze.com 2023-03-08 22:42 出处:网络
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.

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 w开发者_StackOverflowill 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?


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! :-)


It is a simple order of operations issue, pad first then trim to size... like

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


This branches, to be sure, but frankly 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);


You could create an extension of PadRight (or PadLeft) such as:

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


Assuming you want to pad with 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

(on the left), or:

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

(on the right)?


try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消