How to Use Left, Right, Mid Functions in C#

We need Left, Right and Mid functions to get left most right most and mid n characters from a string. Generally, these functions are available in many other programming languages. But these functions are not built in functions in C#. However, you can create your own customized Left(), Right() and Mid() functions in your C# code by using Substring() method of string class and use them accordingly.

C# Left() Function

Below code creates a function Left() to return leftmost n characters of a string.

public static string Left(string str, int length)
{
    if (string.IsNullOrEmpty(str) || length <= 0)
         return string.Empty;

     return str.Substring(0, Math.Min(length, str.Length));
}

Now, you can use Left() function in C# program as given below.

string text = "CodeForDevs";
// Left 4 characters
string left = Left(text, 4);
Console.WriteLine("Left: " + left);  // Output: Left: Code

C# Right() Function

Below code creates a function Right() to return rightmost n characters of a string.

public static string Right(string str, int length)
{
    if (string.IsNullOrEmpty(str) || length <= 0)
    return string.Empty;

    return str.Substring(str.Length - Math.Min(length, str.Length));
}

Now, you can use Right() function in C# program as given below.

string text = "CodeForDevs";
// Right 4 characters
string right = Right(text, 4);
Console.WriteLine("Right: " + right);  // Output: Right: Devs

C# Mid() Function

Below code creates a function Mid() to get n middle characters of a string.

public static string Mid(string str, int startIndex, int length)
{
    if (string.IsNullOrEmpty(str) || length <= 0)
    return string.Empty;

    return str.Substring(startIndex, length);
}

Now, you can use Mid() function in C# program to get n characters from middle of a string. Below example retrieves 3 characters starting from index 4, from string “CodeForDevs”

string text = "CodeForDevs";
string mid = Mid(text, 4, 3);
Console.WriteLine("Mid: " + mid);  // Output: Mid: For

These methods handle edge cases like empty strings and ensure the length does not exceed the string length.

Leave a Reply