How to Find Leftmost String in C#

Haider Ali Feb 02, 2024
How to Find Leftmost String in C#

This guide will learn how to find the leftmost string in C#. How do we return the leftmost substring of the string?

Of course, we’ll have to set a boundary, but how do we do that? Let’s dive in and learn everything about it.

Use the Substring(0,0) Method to Find the Leftmost String in C#

In C#, we can use the myString.Substring(0,0); method. The two parameters are the range of the string that you want to return.

For instance, if you want to return the leftmost string, you need to give a range from 0 to 1, myString.Substring(0,1). Take a look at the following code.

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

namespace left_string {
  class Program {
    static void Main(string[] args) {
      String str = "MARK-ZUKERBERG";
      // # Problem return the leftmost characters of the string
      // with help of substring method i am writing  a left function which will return the leftmost
      // chracter
      Console.WriteLine("LeftMost Character Of String Is :::: " + str.Left());

      Console.ReadKey();
    }
  }
  public static class StringExtensions {
    public static string Left(this string value)  // current String value as a Parameter
    {
      if (string.IsNullOrEmpty(value))
        return value;  // if String is an empty String.

      return (value.Substring(0, 1));
    }
  }
}

Output:

LeftMost Character Of String Is :::: M

In the above code, we created the Left function. Inside that function, we passed the string, attached the Substring(0,0) method, and returned the leftmost range.

That’s quite simple, and that’s how you find a leftmost string.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Related Article - Csharp String