2011-12-28 57 views
1

我在VbScript中有下面的代碼來檢查有效的導航條目。處理C#2.0動態條目的子字符串函數以避免錯誤「索引和長度必須引用字符串中的位置」。

'============================================== 
' Function to test if a given item title is valid navigation item or not 
' Checks for '. ' in the first 5 characters of the title 
'============================================== 
Function CheckValidTitle(ByVal Title) 
    If Len(Title)=0 Then 
     CheckValidTitle=False 
     Exit Function 
    End if 
    If InStr(Left(Title, 6), ". ")>0 Then 
     CheckValidTitle=True 
    Else 
     CheckValidTitle=False 
    End if 
End Function 

如進一步,我在C#2.0寫相同功能的邏輯,以下是代碼:

public static bool CheckValidTitle(string title) 
{ 
    bool retvalue; 
    if (title.Length == 0) 
    { 
     retvalue = false; 
     return retvalue; 
    } 
    string partTitle = title.Substring(0, 5); 

    if (partTitle.Contains(". ")) 
    { 
     retvalue = true; 
    } 
    else 
    { 
     retvalue = false; 
    } 
    return retvalue; 
} 

現在,如果標題是一個長名稱然後上述C#功能工作正常,例如,如果

title = "FAQ Popup New"; //然後正常工作,因爲它是具有長在它超過5個字符,但如果

title = "ASPX"; //它未能作爲字符小於5並給出錯誤「索引和長度必須引用字符串中的位置」。

根據要求,標題名稱將是動態的,並且可以是任何字符數。我很驚訝它如何在VBScript中正常工作,因爲寫入的邏輯是相同的。

我想要經常檢查前5個字符是否有「。」,那麼它是有效的標題,否則它是無效的。

請建議什麼可以是以上問題的最佳解決方案。

謝謝。

回答

2

爲什麼它在VB的原因是因爲在VBScript中Left功能原諒:如果字符串比指定的長度短,它只是默默地選擇可用的長度。在C#中,子字符串函數不能原諒。

解決你的問題,你需要做的就是用下面的替換整個函數:

if(title == null) 
    return false; 
int i = title.IndexOf(". "); 
return i >= 0 && i < 5; 
+0

內我們是否需要檢查!string.IsNullOrEmpty(title)也是? – 2011-12-28 09:30:35

+0

如果標題可能爲空,那麼是的,你應該。但是你的代碼沒有檢查null,所以我決定不檢查。 '空'的情況已經在我的代碼中通過i> = 0的檢查來處理。 – 2011-12-28 09:32:20

+0

是的,可能會出現標題可能爲空的情況,所以我們需要在retvalue = i <5 &&中加上這個! string.IsNullOrEmpty(標題);返回retvalue;請建議! – 2011-12-28 09:34:33

0

嗯,一個解決方案只是在我的腦海中點擊,請建議是否最好。

public static bool CheckValidTitle(string title) 
{ 
    bool retvalue; 
    if (title.Length == 0) 
    { 
     retvalue = false; 
     return retvalue; 
    } 
    string partTitle = title.Substring(0,Math.Min(title.Length,5)); 

    if (partTitle.Contains(". ")) 
    { 
     retvalue = true; 
    } 
    else 
    { 
     retvalue = false; 
    } 
    return retvalue; 
} 

我改變string partTitle = title.Substring(0, 5);string partTitle = title.Substring(0,Math.Min(title.Length,5));,現在是工作的罰款。

請建議!!

+0

是的,這是可行的。但看到我的答案更容易一些。 – 2011-12-28 09:11:49

+0

這是更復雜,然後它需要。你不需要接收子字符串,你只需要知道是否有一個「。」。在前5個字符中,所以IndexOf方法是最好使用的。 – wdavo 2011-12-28 09:12:44

1

您可以使用indexOf方法

if (title.Contains(".") && title.IndexOf(".") < 5) 
{ 
    //there is a . in the first 5 characters 
} 

爲了安全起見你應該檢查該字符串不是空

if (!string.IsNullOrWhiteSpace(title) && title.Contains(".") && title.IndexOf(".") < 5) 
{ 
    //the string is not null or empty and there is a . in the first 5 characters 
} 
+1

這是不正確的;如果在標題中找不到*,* IndexOf將返回-1,*小於5,所以會出現誤報。 – 2011-12-28 09:26:10

+0

我的錯誤。添加一個title.Contains以確保該值存在於標題 – wdavo 2011-12-28 09:35:01

相關問題