2016-07-22 93 views
1

我有字符串,在中間某處(左右不同的長度)我有這個字符序列(有一個空間到左右)分割字符串 - 保留左邊

到:

有沒有去在這一點上分裂,在左側即給定這個字符串返回字符:

下面是一些文字:這裏是的一些文字不同的長度

的結果,我想的是:

下面是一些文字

回答

3

使用IndexOfSubstring結合:

string s = "Here is some text to: and here is some more text of a different length"; 

int length = s.IndexOf("to:"); 

if (length > 0) 
{ 
    s = s.Substring(0, length); 
} 
3

好吧,如果你知道你有這個詞在那裏:

String s = "Here is some text to: and here is some more text of a different length" 
String result = s.Split(new String[] { "to:" })[0]; 

您拆分文本並採取第一部分。

如果您選擇的子字符串不在字符串中,result將只包含普通的s - 無變化。

+0

1.固定,謝謝! 2.如果你有不止一次出現'to:',它只是第一部分。 –

+1

該代碼有效,但它貫穿整個字符串,而IMO是不必要的。 '.IndexOf'&'.SubString'具有更好的性能。 –

+0

@DannyChen無法真正與此爭論,但「Split」更簡單,所以我覺得我也必須展示該解決方案。 –