How do I limit number of characters in a string?

Category: System.Text, viewed: 433 time(s).

By using the StringBuilder object with a defined initial and maximum capacity information we can create a string with a limited number of characters in it. In the code below we set the initial and maximum capacity of the StringBuilder to 20 chars.

using System;
using System.Text;

namespace Kodecsharp.Example.System.Text
{
    class StringLimitLength
    {
        public static void Main(string[] args)
        {
            //
            // Create a string builder with 20 initial and max capacity.
            // This allow us to have a string with maximum 20 chars in
            // length
            //
            StringBuilder builder = new StringBuilder(20, 20);
            builder.Append("ABCDEFGHIJKLMNOPQRST");
            try
            {
                //
                // As this operation can cause exception we need to 
                // catch it.
                //
                builder.Append("U");
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine(builder.ToString());
            Console.ReadLine();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page