Tip C#’s Equivalent to VB’s Left, Right and Mid String

Program4Food

Active member
Joined
Nov 22, 2021
Messages
40
Programming Experience
10+
Coming from decades of BASIC/VB, I need to transition my thinking to how another language performs an equivalent function,
the best way to do this is to bang it out in code. Here is my example of C#’s Equivalent to VB’s Left, Right and Mid String.

I hope a C# beginner finds this useful.



C#:
using System;
using System.Collections.Generic;
using System.Text;

namespace Console_left_right_mid_string
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Example of Left, Right and Mid string in C#");
            Console.WriteLine("by Andrew Daniel - 2021 - VS 2012 - DotNet 2.0\r\n");

            string Result_String,MyText;

            MyText = "This is a line of text";

            Console.WriteLine("The base string of text is \'{0}\' \r\n", MyText);
            
            // Left String
            // https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/left-function
            Result_String = MyText.Substring(0, 7);
            Console.WriteLine("VB's equivalent to Result_String = Left(MyText, 7)");
            Console.WriteLine("\'{0}\' \r\n\r\n", Result_String);
            
            // Right String
            // https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/right-function
            Result_String = MyText.Substring(MyText.Length - 7, 7);
            Console.WriteLine("VB's equivalent to Result_String = Right(MyText, 7)");
            Console.WriteLine("\'{0}\' \r\n\r\n", Result_String);
            
            // Mid String
            // https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/mid-function
            Result_String = MyText.Substring(10, 7);
            Console.WriteLine("VB's equivalent to Result_String = Mid(MyText, 10, 7)");
            Console.WriteLine("\'{0}\' \r\n\r\n", Result_String);

            
            Console.WriteLine("\r\n\r\nPress a key to exit");
            Console.ReadKey();

        }
    }
}
 
And to further blow your mind... Try doing the same thing using C# ranges:


C#:
var text = "This is a line of text";

Console.WriteLine("Left: {0}", text[..7]);
Console.WriteLine("Mid: {0}", text[10..(10+7)]);
Console.WriteLine("Right: {0}", text[^7..]);
 
Last edited:

Latest posts

Back
Top Bottom