HOWTO · Csharp
在 C# 中查找最左边的字符串
在本指南中,我们将学习如何在 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) 方法,并返回了最左边的范围。
这很简单,这就是你找到最左边的字符串的方法。