HOWTO · Csharp
C# で左端の文字列を検索する
このガイドでは、C# で左端の文字列を見つける方法を学習します。
このページの内容
このガイドでは、C# で左端の文字列を見つける方法を学習します。文字列の左端の部分文字列を返すにはどうすればよいですか?
もちろん、境界を設定する必要がありますが、それをどのように行うのでしょうか。飛び込んで、それについてすべてを学びましょう。
C# の Substring(0,0) メソッドを使用して左端の文字列を検索する
C# では、myString.Substring(0,0); 方法を使用できます。2つのパラメーターは、返す文字列の範囲です。
たとえば、左端の文字列を返す場合は、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) メソッドをアタッチして、左端の範囲を返しました。
これは非常に簡単で、左端の文字列を見つける方法です。