在 C# 中查詢最左邊的字串

Haider Ali 2023年10月12日
在 C# 中查詢最左邊的字串

本指南將學習如何在 C# 中查詢最左邊的字串。我們如何返回字串的最左邊的子字串?

當然,我們必須設定一個邊界,但我們該怎麼做呢?讓我們深入瞭解它的一切。

C# 中使用 Substring(0,0) 方法查詢最左邊的字串

在 C# 中,我們可以使用 myString.Substring(0,0); 方法。這兩個引數是你要返回的字串的範圍。

例如,如果你想返回最左邊的字串,你需要給出一個從 0 到 1 的範圍,myString.Substring(0,1)。看看下面的程式碼。

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));
    }
  }
}

輸出:

LeftMost Character Of String Is :::: M

在上面的程式碼中,我們建立了 Left 函式。在該函式中,我們傳遞了字串,附加了 Substring(0,0) 方法,並返回了最左邊的範圍。

這很簡單,這就是你找到最左邊的字串的方法。

作者: 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

相關文章 - Csharp String