字符串.拆分 VB.NET

本文关键字:NET VB 拆分 字符串 | 更新日期: 2023-09-27 18:37:02

我正在尝试在 VB.NET 上做一个String.Split,但它似乎不起作用。感谢任何帮助,看看我错过了什么:

在 C# 中:

sFileContents = File.ReadAllText(f.FullName);
sLines = sFileContents.Split(new string[] { "'r'n" }, StringSplitOptions.RemoveEmptyEntries);

在 VB.NET:

sFileContents = File.ReadAllText(f.FullName)
sLines = sFileContents.Split(New String() {"'r'n"}, StringSplitOptions.RemoveEmptyEntries)

在 C# 中,我得到正确拆分的行数,而在 VB.NET 中,我只得到 1 行。

谢谢

字符串.拆分 VB.NET

转义序列在 VB.NET 中不起作用。

您应该使用以下 VB.NET 常量:vbCrLf,vbLf

sFileContents = File.ReadAllText(f.FullName)
Dim arg() As String = {vbCrLf, vbLf}
sLines = sFileContents.Split(arg, StringSplitOptions.RemoveEmptyEntries)

使用这个:

sFileContents = File.ReadAllText(f.FullName)
sLines = sFileContents.Split({ Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)

另外,请注意,上面的代码中省略了New String()。 VB.NET 可以直接接受{ <element>, <element> }形式的数组。因此不需要 New 关键字和初始值设定项。

事实上,您应该使用Environment.NewLine因为您永远无法确定不同平台上的行尾。

在 VB.NET 中,"'r'n"被解释为"'r'n"本身,而不是像 C# 那样Carriage-Return + NewLine。它们称为特殊字符。VB.NET 没有。只有双引号需要转义(通过使用对)。例如:

Dim result = "He said, ""This is some code.""" 'Yields : He said, "This is some code."

另一种选择是使用预定义的 VB.NET 常量,如vbCrLf但我会说Environment.NewLine是一种更好的方法。