サンプル集  >  C#  >  文字列に指定した文字が含まれるか
文字列に指定した文字が含まれるか
2015/12/25

文字列に指定した文字が含まれるか調べます。

◆環境
OS Windows 7 Professional Service Pack 1 64bit
C# Microsoft Visual C# 2010 01018-587-4111284-70817

[ファイル]-[新規作成]-[プロジェクト]を選択。

[コンソール アプリケーション]を選択し、名前に「MyIdx」と入力し「OK」。

文字列に指定した文字が含まれるかどうかは String.IndexOf で調べることができます。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyIdx
{
    class Program
    {
        static void Main( string[] args )
        {
            string s = "abcdefg";
            DoIt( s, "a" );
            DoIt( s, "ab" );
            DoIt( s, "bc" );
            DoIt( s, "bcd" );
            DoIt( s, "g" );
            DoIt( s, "fg" );
            DoIt( s, "h" );
        }

        static void DoIt( string s1, string s2 )
        {
            Console.WriteLine( s2
                             , s1.IndexOf( s2 )
                             );
        }
    }
}

実行します。

> MyIdx.exe
a       0
ab      0
bc      1
bcd     1
g       6
fg      5
h       -1

文字列の中に指定した文字列が含まれると、その文字列が現れた位置を取得できます。 指定した文字列が含まれない場合 -1 になります。

▲ PageTop  ■ Home


Copyright (C) 2015 ymlib.com