LoginSignup
1
1

More than 1 year has passed since last update.

[C#]ある文字列の中の特定の文字列をループして抜き出す。

Posted at

C#には string.IndexOf() という、ある文字列の中から特定の文字列が最初に出てくるインデックスを返す関数があります。

具体例

Test.cs
using System;
class Program
{
    static void Main()
    {
        string input = "ABCDEFGABCDEFG";

        string t = "EFG";

        // resultには5が格納される
        int result = input.IndexOf(t);
    }
}

しかし、2つ目の"EFG"のIndexは返してくれません。
意外とオンラインのテストで使うことが多いので備忘録も兼ねてループして文字列から特定の文字列を取り出す関数を作りました。

Test2.cs
using System;
class Program
{
    static void Main()
    {
        string input = "ABCDEFGABCDEFG";

        string t = "EFG";

        int count = 0;

        while (count + t.Length <= input.Length) {
            
            // 最初はresに5が入る
            int res = input.IndexOf(t, count);

            if (res == -1)
                return;

            // 5番目からlength分出力
            Console.WriteLine(res + input.Substring(res, t.Length));

            // 次の文字に移動
            count = res + 1;
        }
    }
}

このコードを実行すると、、

4EFG
11EFG

と出力されます。

前の数字はIndex、EFGは特定の文字列として出力されます。

1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1