如何在C#中使用BCL拆分字符串而不丢失分隔符?
我需要根据分隔符的字符数组分割字符串,并且不要在字符串中丢失这些分隔符。即:如何在C#中使用BCL拆分字符串而不丢失分隔符?,c#,.net,string,split,separator,C#,.net,String,Split,Separator,我需要根据分隔符的字符数组分割字符串,并且不要在字符串中丢失这些分隔符。即: string: "Hello world!" separators: " !" result: ("Hello", " ", "world", "!") 当然,我可以编写一些东西来遍历该字符串并返回我所需的结果,但是现在还没有什么东西允许我这样做,比如神奇地配置string.Split Upd:我需要不使用regexp的解决方案,因为它对我来说非常慢。使用正则表达式: string[] parts = Regex.S
string: "Hello world!"
separators: " !"
result: ("Hello", " ", "world", "!")
当然,我可以编写一些东西来遍历该字符串并返回我所需的结果,但是现在还没有什么东西允许我这样做,比如神奇地配置string.Split
Upd:我需要不使用regexp的解决方案,因为它对我来说非常慢。使用正则表达式:
string[] parts = Regex.Split(myString, yourPattern);
测试:
输出:
Hello
" "//just space
World
!
""//empty string
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);
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++;
}
}
var s=“你好,世界!”;
字符[]分隔符={'','!'};
string current=string.Empty;
列表结果=s.Aggregate(新列表(),(列表,ch)=>
{
if(分隔符。包含(ch))
{
列表。添加(当前);
添加(ch.ToString());
current=string.Empty;
}
否则电流+=ch;
退货清单;
},list=>list);
这将是一个纯粹的程序性解决方案:
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);
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++;
}
}
调用Tokenize(输入“!”)
将返回三个令牌:
test
!
!
如果要求两个相邻的分隔符之间应该有一个空标记,那么应该删除
If(currentIdx>startIdx)
条件。如果不需要,我认为不应该使用IgnoreCase
。潜在的性能成本。另外:它完全不能回答问题。-1再次删除。虽然OP也在“”处拆分。想法2可能需要一些解释为什么括号很重要。@Jalal Aldeen Saa'd,查看我的upd关于regexpOne的详细信息:如果源字符串是“”,您希望得到什么输出(一个空字符串和分隔符,或者只有一个空格)?@Dream:我认为使用regex比使用自定义解决方案更快“如果您不倾向于使用一些不安全的上下文和指针”…此外,通过使用正则表达式,您可以避免自定义解决方案中出现的不可预知的错误。。