如何使用多字符分隔符拆分字符串并保持分隔符 [英] How to split a string using a multiple character separator and maintain separator

查看:66
本文介绍了如何使用多字符分隔符拆分字符串并保持分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 VB.NET - 我有一个字符串:

Using VB.NET - I have a string:

"##RES00012##Some value ##RES00034##Another value"

我想使用 "##RES" 作为分隔符来拆分:

That I want to split using the "##RES" as a separator to:

##RES00012## 一些值"##RES00034## 另一个值"

string.split 函数似乎没有提供重载来拆分多个字符或字符数组并维护分隔符,这是功能性目的所必需的.

The string.split function doesn't seem to offer an overload to split on multiple characters or array of characters and maintain the seperator, which is required for functional purposes.

我只是在寻找 indexOf("##res") 并使用字符串操作来执行此操作,除非我遗漏了一些明显的内容?我已经搜索了 SO 以寻找解决方案,但找不到任何真正符合我所追求的方法.

I'm looking at simply searching for indexOf("##res") and using string manipulation to do this unless I'm missing something obvious? I've searched SO for a solution but unable to find anything that actually does what I'm after.

以下是我找到的最接近的:how-do-i-拆分一个字符串由一个多字符分隔符在 c

The following is the closest i've found: how-do-i-split-a-string-by-a-multi-character-delimiter-in-c

推荐答案

拆分多个字符并不是那么棘手;String.Split 方法有重载:

Splitting on multiple characters is not that tricky; there are overloads on the String.Split method that does that:

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

这会给你一个包含两个元素的数组:

This will give you an array with two elements:

"00012## Some value "
"00034## Another value"

但是,分隔符被省略了.不过,这并不过分棘手.它应该放在每个元素之前(如果字符串不以分隔符开头,则第一个除外):

However, the separator is left out. This is not overly tricky though; it should be prepended to each of the elements (except the first one if the string does not start with the separator):

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To parts.Length - 1
    If i > 0 OrElse input.StartsWith("##RES") = True Then
        parts(i) = "##RES" & parts(i)
    End If
Next

这篇关于如何使用多字符分隔符拆分字符串并保持分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆