How do I limit number of characters in a string?

Category: System.Text, viewed: 1K 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();
        }
    }
}
Powered by Disqus