2014-09-25 70 views
0

我試圖檢索海盜的Penzance少將歌(在這裏找到:http://www.naic.edu/~gibson/poems/gilbert1.html)字符串「少將」之前和之後的5個字符。我試圖找到一個比我有更好的方式來做到這一點,並試圖找出爲什麼它不循環。任何想法將不勝感激!VBscript和InStr函數

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 
+3

_「試圖找出它爲什麼不循環」_好,因爲實際上我沒有看到該代碼中的任何循環... – 2014-09-25 16:36:31

+0

不夠公平。這樣做比使用mid()更好嗎?它看起來笨重。 – 2014-09-25 16:55:25

回答

0

它可能會更容易做到這一點是這樣的:

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 

這將得到5個字符的字符串,每個字符串存在時間的左側和右側。

在這種情況下,它將搜索Poem字符串作爲abc並將字符串拆分爲字符串存在的每個部分的數組,然後可以進一步處理它。

+0

非常感謝! – 2014-09-25 16:58:55

+0

不客氣。 – 2014-09-25 17:01:22