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は特定の文字列として出力されます。