2016-05-30 54 views
1

我有兩個字符串如何讓我的串聯字符串的部分早在C#

str1 = "E|DaphneBlake" 
str2 = "8/27/2015" 

它們連接起來以一個。

string str3 = String.Concat(str1,str2) 

這產生一個輸出:

"E|DaphneBlake8/27/2015" 

後來,我想找回這兩個字符串後面爲兩個變種。 我使用此代碼這樣做:

public static string getFirst(string strSource, string strStart, string strEnd) 
{ 
int Start, End; 
if (strSource.Contains(strStart) && strSource.Contains(strEnd)) 
{ 
    Start = strSource.IndexOf(strStart); 
    End = strSource.IndexOf(strEnd); 
    return strSource.Substring(Start, End); 
} 
else 
{ 
    return ""; 
} 
} 


public static string getLast(string strSource, string strStart) 
{ 
int Start, End; 
if (strSource.Contains(strStart)) 
{ 
    Start = strSource.IndexOf(strStart); 
    End = strSource.LastIndexOf(strStart) + 1; 
    return strSource.Substring(Start, End); 
} 
else 
{ 
    return ""; 
} 
} 

string data = getFirst("E|DaphneBlake8/27/2015", "E|Daphne Blake8", "8/27/2015"); 
string data2 = getLast("E|DaphneBlake8/27/2015", "8/27/2015"); 

的getFirst工作,但是getLast不。它給了我一個錯誤

Index and length must refer to a location within the string.Parameter name: length 
+3

閱讀錯誤:「參數名稱:**長度**」。你傳遞的是結束位置,而不是你想要的字符串的長度。 – Blorgbeard

+0

您不顯示'getAfter'的定義。這個電話應該是'getLast'嗎? – DeanOC

+0

@DeanOC,對不起更正了這個問題。 – Harrobbed

回答

-2

如果你有一個標識符是一個字符串的結尾或字符串兩者的開始,那麼你可以使用string.Split(「你的標識符」)

0

我解決上面@Blorgbeard建議的問題。

public static string getAfter(string strSource, string strStart) 
{ 
int Start, End; 
if (strSource.Contains(strStart)) 
{ 
    Start = strSource.IndexOf(strStart); 
    End = strStart.Length; 
    return strSource.Substring(Start, End); 
} 
else 
{ 
    return ""; 
} 
} 
+0

僅有代碼的答案很少。 –

+0

在這種情況下,既然你知道你想直到strSource字符串結束,你可以使用strSource.Substring(Start); – Jimmy