我需要根据分隔符的某些字符数组拆分字符串,并且不会在字符串中丢失这些分隔符。IE:
string: "Hello world!"
separators: " !"
result: ("Hello", " ", "world", "!")
当然,我可以编写一些通过该字符串并返回我需要的结果的东西,但是是否已经有一些东西允许我这样做,比如神奇地配置String.Split
?
Upd:我需要在没有正则表达式的情况下解决,因为它对我来说非常慢。
使用正则表达式:
string[] parts = Regex.Split(myString, yourPattern);
测试:
string[] parts = Regex.Split("Hello World!", "(!| )");
输出:
Hello
" "//just space
World
!
""//empty string
这将是一个纯粹的程序解决方案:
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, "!")
将返回三个令牌:
test
!
!
如果要求两个相邻分隔符之间应有一个空标记,if (currentIdx > startIdx)
则应删除该条件。
一个 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);