如何在c#內使用vb的left、right函數

  • 102
  • 0

原本只內建在VB language才有的string Left、Right要如何在c#中也能使用

最快的方法就是在共用區中新增一個靜態的class就能使用

public static class StringExtensions
    {
        public static string Left(this string value, int maxLength)
        {
            if (string.IsNullOrEmpty(value)) return value;
            maxLength = Math.Abs(maxLength);

            return (value.Length <= maxLength
                   ? value
                   : value.Substring(0, maxLength)
                   );
        }
        /// 

        /// Returns the last few characters of the string with a length
        /// specified by the given parameter. If the string's length is less than the 
        /// given length the complete string is returned. If length is zero or 
        /// less an empty string is returned
        /// 
        /// the string to process/// Number of characters to return/// 
        public static string Right(this string s, int length)
        {
            length = Math.Max(length, 0);

            if (s.Length > length)
            {
                return s.Substring(s.Length - length, length);
            }
            return s;
        }
    }

實際操作案例

string MyStr = "test";
MyStr.Left(MyStr.Length - 1);
MyStr.Right(MyStr.Length - 1);