功能:string.Substring(startIndex, length)改良
原因:當StartIndex + length > string.Length時會發生錯誤,但程式執行時有時不知道字長度,造成錯誤,很麻煩,只好自己改良了
語法:
public static string SubString(string strData, int startIndex, int length) { int intLen = strData.Length; int intSubLen = intLen - startIndex; string strReturn; if (length == 0) strReturn = ""; else { if (intLen <= startIndex) strReturn = ""; else { if (length > intSubLen) length = intSubLen; strReturn = strData.Substring(startIndex, length); } } return strReturn; } |
範例:
string strReturn = "";
string strData = "0123456789";
strReturn = Substring(strData, 0, 0 ); // ""
strReturn = Substring(strData, 0, 12); // "0123456789"
strRetrun = Substring(strData, 13, 10); // ""
strReturn = Substring(strData, 9, 3); // "9"
strReturn = Substring(strData, 0, 3); //"012"
沒有留言:
張貼留言