如何在 C# 中使用 BCL 拆分字符串而不丢失分隔符?
我需要根据某些分隔符字符数组分割字符串,并且不要丢失字符串中的这些分隔符。即:
string: "Hello world!"
separators: " !"
result: ("Hello", " ", "world", "!")
当然,我可以编写一些东西来遍历该字符串并返回我需要的结果,但是是否已经有一些东西允许我这样做,比如神奇地配置了String.Split
?
更新:我需要在没有正则表达式的情况下解决问题,因为它对我来说非常慢。
I need to split a string based on some character array of separators and not lose these separators in string. I.e.:
string: "Hello world!"
separators: " !"
result: ("Hello", " ", "world", "!")
Of course, i can write something that goes through that string and returns me needed result, but isn't there something already allowing me to do this, like magically configured String.Split
?
Upd: I need to solution without regexp, because it is very slow for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用正则表达式:
测试:
输出:
Use regular expression:
Test:
output:
一个linq解决方案:
A linq solution:
这将是一个纯粹的程序解决方案:
请注意,此解决方案避免返回空令牌。例如,如果输入为:
调用
Tokenize(input, "!")
将返回三个标记:如果要求两个相邻分隔符之间应有一个空标记,则
if (currentIdx > startIdx)
条件应该被删除。This would be a purely procedural solution:
Note that this solution avoids returning empty tokens. For example, if the input is:
calling
Tokenize(input, "!")
will return three tokens:If the requirement is that two adjacent separators should have an empty token between them, then the
if (currentIdx > startIdx)
condition should be removed.