Cuts off a string given a certain input amount, useful for ensuring the user never enters more than possible into a given field. - CSharp System

CSharp examples for System:String Shorten

Description

Cuts off a string given a certain input amount, useful for ensuring the user never enters more than possible into a given field.

Demo Code


using System.Text;
using System;//  ww w. j  av  a2 s  .com

public class Main{
        /// <summary>
        ///     Cuts off a string given a certain input amount, useful for ensuring the user never enters more than possible into a
        ///     given field.
        /// </summary>
        /// <param name="value">String that needs to be truncated to max length.</param>
        /// <param name="maxLength">Negative values will cause exception.</param>
        /// <returns>Truncated string.</returns>
        public static string Truncate(this string value, int maxLength)
        {
            if (string.IsNullOrEmpty(value)) return value;
            return value.Length <= maxLength ? value : value.Substring(0, maxLength);
        }
}

Related Tutorials