これは純粋に手続き的な解決策になります。
private static IEnumerable<string> Tokenize(string text, string separators)
{
int startIdx = 0;
int currentIdx = 0;
while (currentIdx < text.Length)
{
// found a separator?
if (separators.Contains(text[currentIdx]))
{
// yield a substring, if it's not empty
if (currentIdx > startIdx)
yield return text.Substring(startIdx, currentIdx - startIdx);
// yield the separator
yield return text.Substring(currentIdx, 1);
// mark the beginning of the next token
startIdx = currentIdx + 1;
}
currentIdx++;
}
}
このソリューションは、空のトークンを返さないようにすることに注意してください。たとえば、入力が次の場合:
string input = "test!!";
呼び出すと、 Tokenize(input, "!")3つのトークンが返されます。
test
!
!
隣接する2つのセパレーターの間に空のトークンを含める必要がある場合は、if (currentIdx > startIdx)条件を削除する必要があります。