The String extension prevents you from suffering from single-and double-byte problems when using PadLeft and PadRight.
In NET, the Length of a string does not distinguish whether the character contained in the current string is a single or dubyte character, as a result, when we use the PadLeft and PadRight methods of strings to process some strings that require typographical display, the related display will be uneven, so here we have such an extension, let the double byte display occupy two single byte width "vomit", the following is the specific code
Using System. text. regularExpressions; public static class StringExtensions {// <summary> /// fill the length to the left by single-byte string /// </summary> /// <param name = "input"> </param> /// <param name = "length"> </param> /// <param name = "paddingChar"> </param> /// <returns> </returns> public static string PadLeftWhileDouble (this string input, int length, char paddingChar = '\ 0') {var singleLength = GetSingleLength (input); return input. padLeft (length-singleLength + input. length, paddingChar);} private static int GetSingleLength (string input) {if (string. isNullOrEmpty (input) {throw new ArgumentNullException ();} return Regex. replace (input, @ "[^ \ x00-\ xff]", "aa "). length; // calculate the length of the single-byte string corresponding to the string} // <summary> // fill the length to the right of the single-byte string /// </summary> // <param name = "input"> </param> // <param name = "length"> </param> // <param name = "paddingChar"> </param >/// <returns> </returns> public static string PadRightWhileDouble (this string input, int length, char paddingChar = '\ 0') {var singleLength = GetSingleLength (input); return input. padRight (length-singleLength + input. length, paddingChar );}}
The test code is as follows:
Console. writeLine ("123 test ". padRightWhileDouble (25) + "1"); Console. writeLine ("123 test ". padRightWhileDouble (25, 'A') + "1"); Console. writeLine ("1231212 ". padRightWhileDouble (25) + "1"); Console. writeLine ("1231212 ". padRightWhileDouble (25, 'A') + "1"); Console. writeLine ("123 test ". padLeftWhileDouble (25) + "1"); Console. writeLine ("123 test ". padLeftWhileDouble (25, 'A') + "1"); Console. writeLine ("1231212 ". padLeftWhileDouble (25) + "1"); Console. writeLine ("1231212 ". padLeftWhileDouble (25, 'A') + "1 ");
Test