简体   繁体   中英

VBscript and InStr function

I'm trying to retrieve the 5 characters before and after the string "Major-General" in the Pirate's of Penzance Major-General Song (found here: http://www.naic.edu/~gibson/poems/gilbert1.html ). I'm trying to find a better way to do this than what I have and also trying to figure out why it isn't looping. Any ideas would be greatly appreciated!

l1 =INSTR(l2, string, "Major-General")
l2 = 5
l3 = 1
vcount=0

if vcount <5 then
    l1 =INSTR(l3, string, "Major-General")
    vcount = vcount +1 
    word = mid(string, l1-5, l2 )
    word1 = mid(string, l1+13, l2)
    l3 = l3+l1
    response.write "<br>" & "5 before: " & word & "<br>"  & "5 after: " & word1 
end if

It may be easier to do it like this:

Dim Poem,aStr,i,block,Left5,Right5

Poem = "The abc poem is abc in this abc string."

aStr = Split(Poem,"abc")

If uBound(aStr) = 0 Then Response.Write "String not found": Response.End

For i = 0 to uBound(aStr)
  block = Trim(aStr(i))
  Left5 = "": Right5 = ""
  if cStr(i) <> cStr(uBound(aStr)) then Left5 = Right(block,5)
  If cStr(i) <> cStr(0) then Right5 = Left(block,5)

  Response.Write "The 5 characters to the left of abc:" & Left5
  Response.Write "The 5 characters to the right of abc:" & Right5

Next

This will get the 5 characters to the left and right of the string, each time the string exists.

In this case, it will search the Poem string for abc and split the string into an array of each part where the string exists, then it can be processed further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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