2

区切り文字の文字配列に基づいて文字列を分割し、文字列内のこれらの区切り文字を失わないようにする必要があります。すなわち:

string: "Hello world!"
separators: " !"
result: ("Hello", " ", "world", "!")

もちろん、その文字列を調べて必要な結果を返すものを書くことはできますが、魔法のように構成されているように、これを可能にするものはすでにありませんString.Splitか?

Upd:私にとっては非常に遅いので、正規表現なしで解決する必要があります。

4

3 に答える 3

3

正規表現を使用します。

string[] parts = Regex.Split(myString, yourPattern);

テスト:

string[] parts = Regex.Split("Hello World!", "(!| )");

出力:

Hello
" "//just space
World
!
""//empty string
于 2011-07-26T07:02:45.793 に答える
2

linqソリューション:

var s = "Hello world!";
char[] separators = { ' ', '!' };

string current = string.Empty;
List<string> result = s.Aggregate(new List<string>(), (list, ch) =>
    {
        if (separators.Contains(ch))
        {
            list.Add(current);
            list.Add(ch.ToString());
            current = string.Empty;
        }
        else current += ch;
        return list;
    }, list => list);
于 2011-07-26T07:19:12.043 に答える
2

これは純粋に手続き的な解決策になります。

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)条件を削除する必要があります。

于 2011-07-26T09:07:47.393 に答える