我有关于以下代码的堆栈溢出问题:
For Each DeltaCharB As Char In DeltaString
If DeltaCharB = "[" Then
Dim DeltaIndexB As Integer = TB8.IndexOf("[B|")
Dim DeltaStringB As String = TB8.Substring(DeltaIndexB + 3, TB8.IndexOf("]", DeltaIndexB + 1) - DeltaIndexB - 3)
MsgBox(DeltaStringB)
Else
'Do nothing
End If
Next
创建的问题是,如果代码运行X次,发现字符“[”,则字符串在消息框中显示相同的X次。
但是我只想让它处理1X。我试图更改以下行,但我预计一次只允许一个字符。
If DeltaCharB = "[B|" Then
通常,用于搜索的字符串如下:
{[A|Text belonging to entry A][B|Text belonging to entry B][C|Text belonging to entry C]}.... ect...ect
任何人都知道如何解决这个问题?
答案 0 :(得分:3)
为什么需要循环?你的分隔符定义明确,你可以这样做:
Function GetContent(byval input as string, byval delimiter as string) as string
Dim fullDelimiter = "["& delimiter &"|"
Dim BeginPosition as Integer = input.IndexOf(fullDelimiter)
if BeginPosition > -1 then
BeginPosition += fullDelimiter.Length
Dim EndPosition = input.IndexOf("][", BeginPosition)
if EndPosition > -1 then
return input.SubString(BeginPosition, EndPosition - BeginPosition)
end if
end if
return ""
End Function
用法:
Dim s as string = "[A|Text belonging to entry A][B|Text belonging to entry B][C|Text belonging to entry C]"
Dim content = GetContent(s, "B")
内容现在包含“属于条目B的文字”
请注意,使用此代码,分隔符可以是[
和|
之间任意长度的字符串。
适合任何输入格式的更通用的解决方案意味着也接受函数中的结束分隔符:
Function GetContent(byval input as string, byval FromDelimiter as string, byval ToDelimiter as string) as string
Dim BeginPosition as Integer = input.IndexOf(FromDelimiter)
if BeginPosition > -1 then
BeginPosition += FromDelimiter.Length
Dim EndPosition = input.IndexOf(ToDelimiter, BeginPosition)
if EndPosition > -1 then
return input.SubString(BeginPosition, EndPosition - BeginPosition)
end if
end if
return ""
End Function