2012-02-13 87 views
0

我有一個簡短的測試程序來提取由製表符分隔的字符串。輸出對我來說沒有意義。這個想法是找到下一個標籤位置,並返回上一個和下一個標籤之間的值。ColdFusion,試圖解析製表符分隔的字符串

我的程序輸出如下。 「搶劫」從哪裏來?

 
    fred  ted rob a rob alex 

程序

<cfscript> 
    s="fred"&chr(9)&"ted"&chr(9)&"rob"&chr(9)&"alex"; 

    oldp=0; 
    while(oldp<Len(s)) 
    { 
     p=Find(chr(9),s,oldp+1); 
     if (p==0) 
      break; 
     m=Mid(s,oldp+1,p); // oldp is the old tab poit p is the new get string in between 
     WriteOutput(m); 
     WriteOutput(" "); 
     oldp=p; 
    } 
</cfscript> 

現在,如果我改變程序的每個字符串的結果是後打印出來oldp

fred => 1 
ted rob a => 6 
rob alex => 10 

我希望看到1,5,9,。我不明白爲什麼ted rob是第二個字符串。我期望看到rob

+0

不要忘記使用代碼標籤'{...}',以便您的代碼片段正確顯示。 – Leigh 2012-02-13 03:03:13

回答

6
Mid(s,oldp+1,p); 

要回答你的問題,那就是沒怎麼mid作品。第三個參數p是要返回的字符數,而不是字符串中的位置。

mid(s, 6, 3) ; // this would return "Ted" 

如果我可以提出一個建議 - 將字符串視爲一個列表,用標籤分隔很容易。然後用列表函數解析它。

<cfscript> 
    str = "red"& chr(9) &"ted"& chr(9) &"rob"& chr(9) &"alex"; 
    for (i = 1; i <= listLen(str, chr(9)); i++) { 
     WriteDump(listGetAt(str, i, chr(9))); 
    } 
</cfscript> 

請注意,大多數列表函數忽略空元素。如果你想保留它們,請使用listToArray

<cfscript> 
    str = "red"& chr(9) &"ted"& chr(9) &"rob"& chr(9) &"alex"; 
    arr = listToArray(str, chr(9), true); 
    for (i = 1; i <= arrayLen(arr); i++) { 
     WriteDump(arr[i]); 
    } 
</cfscript> 
+0

嗨,你的想法就像列表一樣對待它,好得多我的,謝謝你的提示。 – 2012-02-13 12:28:38