【问题标题】:VB.NET String.Split method?VB.NET String.Split 方法?
【发布时间】:2011-10-27 16:34:37
【问题描述】:

我在使用 String.Split 方法时遇到了一些问题,示例如下:

Dim tstString As String = "something here -:- URLhere"
Dim newtstString = tstString.Split(" -:- ")
MessageBox.Show(newtstString(0))
MessageBox.Show(newtstString(1))

上面的内容,在 PHP(我的母语!)中会在消息框中返回一些 here 和 URLhere 的内容。

在 VB.NET 中我得到:

something here

: (colon)

String.Split 是否仅适用于标准字符?我似乎无法弄清楚这一点。不过,我敢肯定这是非常简单的事情!

【问题讨论】:

  • 我已经通过将行更改为: Dim newtstString = Split(ts​​tString, "-:-") 虽然我仍然不确定为什么 String.Split 不能正常工作。
  • 查看 msdn.microsoft.com/en-us/library/system.string.split.aspx 了解 string.split() 的所有重载
  • 我在调查String.Split is not removing the split text, only the first letter 之后来到这里,当我运行您的代码时newTstString{ "something", "here", "-:-", "URLhere" },这是我现在所期望的,因为我知道tstString.Split(" -:- ") 在功能上是等效的到tstString.Split(" ")。这个问题中列出的输出是运行tstString.Split("-") 会得到的结果,尽管结果数组中会有第三个元素" URLhere"

标签: .net regex vb.net split


【解决方案1】:

这是您需要做的,以防止字符串被转换为Char 数组。

    Dim text As String = "something here -:-  urlhere"
    Dim parts As String() = text.Split(New String() {" -:- "}, StringSplitOptions.None)

这是你在这种情况下需要使用的System.String成员函数

Public Function Split(ByVal separator As String(), ByVal options As StringSplitOptions) As String()

【讨论】:

  • 需要注意的是,它不会将字符串转换为Char数组,而是使用字符串的第一个字符,并且只将单个字符传递给this Split overload。当您让 VB 将 String 隐式转换为 Char 时会发生这种情况,这也是拥有 Option Strict On 的另一个原因。
猜你喜欢
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 2011-10-24
  • 1970-01-01
  • 2013-07-18
相关资源
最近更新 更多