C# Left / Right / Mid String Functions (as in Visual Basic.Net)

Visual Basic’s left, right, mid functions are nifty tricks that can be easily implemented in C#.

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

namespace ConsoleApplication1
{
    public class Test
    {
        public static String left(String input, int len)
        {
            return input.Substring(0, len);
        }

        public static String right(String input, int len)
        {
            return input.Substring(input.Length - len);
        }

        public static String mid(String input, int index, int len)
        {
            return input.Substring(index - 1, index + len - 1);
        }

        public static String mid(String input, int index)
        {
            return input.Substring(index - 1);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            String str1 = "left string";
            Console.WriteLine("Test left str: " + str1);
            Console.WriteLine("Test left str: " + Test.left(str1, 4));

            String str2 = "right string";
            Console.WriteLine("Test right str: " + str2);
            Console.WriteLine("Test right str: " + Test.right(str2, 6));

            String str3 = "mid string";
            Console.WriteLine("Test mid str: " + str3);
            Console.WriteLine("Test mid str: " + Test.mid(str3, 2, 6));

            Console.WriteLine("Test mid str: " + str3);
            Console.WriteLine("Test mid str: " + Test.mid(str3, 5));
            Console.ReadKey();
        }
    }
}

Output:
Test left str: left string
Test left str: left
Test right str: right string
Test right str: string
Test mid str: mid string
Test mid str: id stri
Test mid str: mid string
Test mid str: string

2 thoughts on “C# Left / Right / Mid String Functions (as in Visual Basic.Net)”

Leave a Reply