.NET 字符串分割方法奇怪的行为
我在使用 .NET 3.5 时遇到 string.split 问题:
要分割的字符串是:
dim source as string = "ab|foo|bar|bar|bar-foo|ab|ezrezertr|ghghhjhj|ab|foo|xxx|"
dim result() as string = source.split("ab|")
在 Winforms 应用程序中使用时,结果是“正确”:
结果(0)是“foo|bar|bar|bar-foo|”
结果(1)是“ezrezertr|ghghhjhj|”
结果(2)是“foo | xxx |”
我很高兴!
当在 ASP.NET 代码后面使用时,结果是: result
(0) is "b|foo|bar|bar|bar-foo|"
结果(1)是“b|ezrezertr|ghghhjhj|”
结果(2)是“b | foo | xxx |”
换句话说, split 函数仅删除分隔符字符串的第一个字符! 有人知道为什么吗?
I have a problem with string.split using.NET 3.5:
String to split is:
dim source as string = "ab|foo|bar|bar|bar-foo|ab|ezrezertr|ghghhjhj|ab|foo|xxx|"
dim result() as string = source.split("ab|")
When used within a Winforms applicaton, the result is "correct":
result(0) is "foo|bar|bar|bar-foo|"
result(1) is "ezrezertr|ghghhjhj|"
result(2) is "foo|xxx|"
And I'm happy!
When used within an ASP.NET code behind, the result is:
result(0) is "b|foo|bar|bar|bar-foo|"
result(1) is "b|ezrezertr|ghghhjhj|"
result(2) is "b|foo|xxx|"
In other words, the split function only get rid of the 1st character of the separator string!
Does someone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ASP.NET 结果看起来像您正在使用 <代码>Regex.Split而不是
String.Split
。字符串"ab|"
将被解释为“a”后跟“b”或什么都没有的正则表达式,因此只有“a”匹配。稍后:第二种理论:
String.Split
重载。唯一的单个参数重载采用char
数组。String.Splt(char())
将根据任何 传递的字符进行拆分。因此,我认为在 ASP.NET 情况下,您没有
option strict on
,因此theString.Split(anotherString)
被视为theString.Split( anotherString.ToCharArray())
。因此仅拆分
"b"
。然而,这留下了第一种情况如何作为传递字符串的问题,但没有在没有额外参数的情况下采用
String()
的重载(SplitOptions
)...摘要: Visual Basic 在文件/项目/语言级别设置的额外隐式转换和行为可以使相同的代码表现不同。
The ASP.NET results look like you are using
Regex.Split
rather thanString.Split
. The string"ab|"
will be interpreted as a regular expression for "a" followed by "b" or nothing, so just an "a" matches.Later: Second Theory:
String.Split
that takes a single string argument. The only single argument overload takes an array ofchar
.String.Splt(char())
will split on any of the passed characters.Option Strict On
will implicitly convert a string to an array of chars.Hence I think in the ASP.NET case you don't have
option strict on
, thereforetheString.Split(anotherString)
is being treated astheString.Split(anotherString.ToCharArray())
.Thus splitting on just a
"b"
.However this leaves the question of how the first cases acts as passing a string, but there is no overload taking a
String()
without extra parameters (aSplitOptions
)...Summary: Visual Basic's extra implicit conversions and behaviour set at a file/project/language level can make identical code behave differently.
如果输入字符串相同,那么我几乎可以向您保证控制台应用程序和 ASP.NET 的 split 方法的行为相同。
也许输出显示不正确?
If the input string is the same, then I can nearly guarantee you that the split method of a Console app and ASP.NET behave the same.
Maybe the output is not displayed correctly?