Sunday, 26 January 2014

Substring Safe method for a string to a get the substring when out of index length C#

In this article we are going to see how to create a safe method for the substring when user wrongly gives the length of the substring that is too much large result in a "OutOfIndex Exception". For this we are going to see how to create a safe substring method for string manipulation.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringManip
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Rajesh";

            /* Predefined Method */
            try
            {
                Console.WriteLine(" Substring :- {0} \n",name.Substring(1,3));
                Console.WriteLine(name.Substring(1, 10));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine();
            /* User defined Safe Method */
            Console.WriteLine(" Substring :- {0} \n",name.SubString(1,10));
            Console.Read();

        }
    }

    static class StringExtension
    {
        public static string SubString(this string input,int startindex)
        {
            int length = input.Length;
            return SubString(input, startindex, length - startindex);           
        }

        public static string SubString(this string input, int startindex, int length)
        {
            int whole = input.Length;
            if(!(length <= whole - startindex))
            {
                length = whole - startindex;
            }
            return input.Substring(startindex, length);
        }
    }
}



When you see the output Index and length must refer to a location  error when try to get the string for length 10 by predefined method, but by user defined method we are safe method the substring up to the length of the string

Output:

 Substring :- aje

Index and length must refer to a location within the string.
Parameter name: length

 Substring :- ajesh




I Hope this article will help you to understand how to create a safe method for substring method of a string.

No comments:

Post a Comment