VB.NET,用 foreach returns 1 在文本中搜索字长,即使它不在其中
VB.NET, Search for word length in text with a foreach returns 1 even if it is not in it
所以我遇到了一个奇怪的问题,我无法直接指出是什么原因造成的。在我的 Outlook 应用程序中,我创建了一个加载项 (Visual Studio - VB.NET),用于搜索正文中的单词(它搜索诸如问候之类的结束标记)。
这些'Closing tags'设置在一个数组中。它的作用是:将 body 设置为文本的正文,但是当找到结束标记时,只需将正文文本设置为结束标记。
然而问题是,如果数组到达其末尾,并且未找到数组字符串,那么它总是会运行另一次(数组为 4 意味着它运行第五次 ??)并设置长度为 1 而它应该为 0(未找到)。
字符串的搜索是使用 Instr 函数完成的,主体的切割是使用 Left 函数完成的(从找到结束标记的位置开始)。
这里是使其可视化的代码部分:
Dim BodyText As String
BodyText = oitem.Body
Dim ClosingTags(4) As String
ClosingTags(0) = "regards"
ClosingTags(1) = "your sincerely"
ClosingTags(2) = "yours truly"
ClosingTags(3) = "best wishes"
Dim MailClosing As String
Dim BodyUntil As String
For Each element In ClosingTags
MailClosing = InStr(LCase(BodyText), LCase(element))
If MailClosing <> 0 Then
BodyTextUntil = Left(BodyText, InStr(LCase(BodyText), LCase(element)) - 1)
BodyText = BodyTextUntil
Exit For
Else
BodyText = oitem.Body
End If
Next element
如果用户在正文中使用结束标记,此功能将正常工作。尽管当他们只是键入没有结束标记的文本时,它会出现故障。然后会发生什么:
- foreach 循环,找不到结束标记,所以它一直循环。
- 通常它应该循环 4 次(数组 = 4)但是当找不到标签时它会以某种方式循环第五次并将
MailClosing
变量设置为 1,这会导致 IF 条件为真而它应该是假的,从而将正文设置为空(因为结束标记位于位置 1 并在 1 -1 = 0 之后切断所有内容)。
问题是,是什么原因造成的,如何解决?也许使用 a for 1 - 4(等于数组长度?)
Dim ClosingTags(4) As String
这将创建一个包含 5 个元素的数组(4 是最大索引,而不是项目的数量)
使用 3:
Dim ClosingTags(3) As String
ClosingTags(0) = "regards"
ClosingTags(1) = "your sincerely"
ClosingTags(2) = "yours truly"
ClosingTags(3) = "best wishes"
所以我遇到了一个奇怪的问题,我无法直接指出是什么原因造成的。在我的 Outlook 应用程序中,我创建了一个加载项 (Visual Studio - VB.NET),用于搜索正文中的单词(它搜索诸如问候之类的结束标记)。
这些'Closing tags'设置在一个数组中。它的作用是:将 body 设置为文本的正文,但是当找到结束标记时,只需将正文文本设置为结束标记。
然而问题是,如果数组到达其末尾,并且未找到数组字符串,那么它总是会运行另一次(数组为 4 意味着它运行第五次 ??)并设置长度为 1 而它应该为 0(未找到)。
字符串的搜索是使用 Instr 函数完成的,主体的切割是使用 Left 函数完成的(从找到结束标记的位置开始)。
这里是使其可视化的代码部分:
Dim BodyText As String
BodyText = oitem.Body
Dim ClosingTags(4) As String
ClosingTags(0) = "regards"
ClosingTags(1) = "your sincerely"
ClosingTags(2) = "yours truly"
ClosingTags(3) = "best wishes"
Dim MailClosing As String
Dim BodyUntil As String
For Each element In ClosingTags
MailClosing = InStr(LCase(BodyText), LCase(element))
If MailClosing <> 0 Then
BodyTextUntil = Left(BodyText, InStr(LCase(BodyText), LCase(element)) - 1)
BodyText = BodyTextUntil
Exit For
Else
BodyText = oitem.Body
End If
Next element
如果用户在正文中使用结束标记,此功能将正常工作。尽管当他们只是键入没有结束标记的文本时,它会出现故障。然后会发生什么:
- foreach 循环,找不到结束标记,所以它一直循环。
- 通常它应该循环 4 次(数组 = 4)但是当找不到标签时它会以某种方式循环第五次并将
MailClosing
变量设置为 1,这会导致 IF 条件为真而它应该是假的,从而将正文设置为空(因为结束标记位于位置 1 并在 1 -1 = 0 之后切断所有内容)。
问题是,是什么原因造成的,如何解决?也许使用 a for 1 - 4(等于数组长度?)
Dim ClosingTags(4) As String
这将创建一个包含 5 个元素的数组(4 是最大索引,而不是项目的数量)
使用 3:
Dim ClosingTags(3) As String
ClosingTags(0) = "regards"
ClosingTags(1) = "your sincerely"
ClosingTags(2) = "yours truly"
ClosingTags(3) = "best wishes"