C#を使ってstringで定義した文字列の先頭要素をチェックします。
StringクラスのStartsWithメソッドを使います。
使い方
string s = "Hello, My Friend!";
if(s.StartsWith("Hello")){
// 一致
}
else{
// 不一致
}
引数に指定した文字列と先頭要素が一致した場合、trueを返し、一致しなかった場合にFalseを返します。
実際の例です。(プロジェクトは、コンソールアプリで作成してください)
以下のプログラムでは、キーボードから入力した電話番号の先頭をチェックして「090」「080」「070」だったら携帯電話と判定しています。
Program.cs
using System;
namespace 文字列の先頭要素をチェックする
{
class Program
{
static void Main(string[] args)
{
string cellNumber;
Console.Write("電話番号を入れてね: ");
cellNumber = Console.ReadLine();
Console.WriteLine("入力した番号: {0}", cellNumber);
// 文字列の先頭をチェック
if (cellNumber.StartsWith("090") || cellNumber.StartsWith("080") || cellNumber.StartsWith("070"))
{
Console.WriteLine("携帯電話です");
}
else
{
Console.WriteLine("一般電話です");
}
}
}
}
コメント