Search code examples
c#substring

string.substring vs string.take


If you want to only take a part of a string, the substring method is mostly used. This has a drawback that you must first test on the length of the string to avoid errors. For example you want to save data into a database, and want to cut off a value to the first 20 characters.

If you do temp.substring(0,20) but temp only holds 10 chars, an exception is thrown.

There are 2 solutions that I see :

  1. test on the length, and do the substring if needed
  2. use the extension method Take

        string temp = "1234567890";
        var data= new string( temp.Take(20).ToArray());
        --> data now holds "1234657890"
    

Is there any disadvantage in terms of speed or memory use , when one uses the Take method. The benefit is that you do not have to write all those if statements.


Solution

  • If you find yourself doing this a lot, why not write an extension method?

    For example:

    using System;
    
    namespace Demo
    {
        public static class Program
        {
            public static void Main(string[] args)
            {
                Console.WriteLine("123456789".Left(5));
                Console.WriteLine("123456789".Left(15));
            }
        }
    
        public static class StringExt
        {
            public static string Left(this string @this, int count)
            {
                if (@this.Length <= count)
                {
                    return @this;
                }
                else
                {
                    return @this.Substring(0, count);
                }
            }
        }
    }