简体   繁体   English

使用2个字符分割字符串

[英]Splitting a String using 2 Characters

I'm currently splitting on periods in my code, but found a few issues when I ran it. 我目前在代码中使用句点,但是在运行时发现了一些问题。 I was wondering how I could split on ". " instead of just "." 我想知道如何分割“。”而不是“。”。

Current Code: 当前代码:

Dim words As String() = item.Split(New Char() {"."c})

Dream Code: 梦代码:

Dim words As String() = item.Split(New Char() {". "c})

It doesn't allow me to add that extra space in after the period, is there a workaround? 它不允许我在句点之后添加额外的空间,是否有解决方法?

To expand on that, see how Replace is used first? 要对此进行扩展,请参阅如何首先使用“ Replace First you turn the 2 characters into one that is going to be uniquely identifiable, and then you can split it effectively. 首先,您将2个字符变成一个唯一可识别的字符,然后可以对其进行有效分割。

Dim words As String() = item.Replace(". ", "|").Split(New Char() {"|"c})

And you can probably simplify it even more like this: 您可能甚至可以这样简化它:

Dim words As String() = item.Replace(". ", "|").Split("|"c)

That assumes you are using Option Strict On - if not, you can simplify it more like this as the string will be converted to a char automatically: 假设您正在使用Option Strict On否则,您可以像这样进一步简化它,因为字符串将自动转换为char:

Dim words As String() = item.Replace(". ", "|").Split("|")

You should use the String.Split Method (String(), StringSplitOptions) overload of String.Split: 您应该使用String.Split的String.Split方法(String(),StringSplitOptions)重载:

Dim s = "1. 2. 3. 4.5.6"
Dim a = s.Split({". "}, StringSplitOptions.None)
Console.Write(String.Join(vbCrLf, a))

outputs: 输出:

1
2
3
4.5.6

(Depending on the version of Visual Studio, you might need something like New String() {". "} instead of {". "} .) (取决于Visual Studio的版本,您可能需要类似New String() {". "}而不是{". "} 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM