Exemplo n.º 1
0
        public static string CompactString(string value, int maxLength, CompactStringBehavior behavior, string snipIndicator)
        {
            string compacted        = string.Empty;
            int    lenghtAdjustment = 0;

            snipIndicator = " " + snipIndicator;
            if (maxLength <= 0)
            {
                throw new ArgumentOutOfRangeException("maxLength", maxLength, "Value must be greater than zero (0).");
            }
            if (behavior == 0)
            {
                throw new ArgumentException("behavior must contain a value other than 0.", "behavior");
            }
            if (value.Length <= maxLength)
            {
                return(value);
            }
            if (behavior == CompactStringBehavior.removeEnd)
            {
                compacted = value.Substring(0, maxLength - snipIndicator.Length) + snipIndicator;
            }
            else if (behavior == CompactStringBehavior.removeMiddle)
            {
                if (Math.IEEERemainder(maxLength, 2) != 0)
                {
                    lenghtAdjustment += 1;
                }
                compacted  = value.Substring(0, System.Convert.ToInt32(Math.Floor(maxLength / 2.0)) - snipIndicator.Length - lenghtAdjustment) + snipIndicator;
                compacted += value.Substring(value.Length - System.Convert.ToInt32(Math.Floor(maxLength / 2.0)), System.Convert.ToInt32(Math.Floor(maxLength / 2.0)));
            }
            else
            {
                throw new ArgumentException(string.Format("Unrecognized CompactStringBehavior '{0}'.", behavior.ToString()));
            }
            if (compacted.Length > maxLength)
            {
                throw new Exception(string.Format("Compact of string resulted in a string exceeding "
                                                  + "the requested maximum length. Expected length: {1}, actual: {2}. "
                                                  + "String value: \"{0}\".",
                                                  value,
                                                  maxLength.ToString(),
                                                  compacted.Length.ToString()));
            }
            return(compacted);
        }
Exemplo n.º 2
0
 public static string CompactString(string value, int maxLength, CompactStringBehavior behavior)
 {
     return(CompactString(value, maxLength, behavior, "..."));
 }