2011-07-11 8 views
4

我如何獲得在逗號(,)之前的所有元素在c#中的字符串? 例如 如果我的字符串是說在c中的字符串中的最後一個逗號前的所有元素#

string s = "a,b,c,d"; 

那麼我想最後comma.So前d即之前的所有元素我的新字符串喊的樣子

string new_string = "a,b,c"; 

我試圖分裂,但與我可以一次只有一個特定元素。

回答

8
string new_string = s.Remove(s.LastIndexOf(',')); 
+0

嘿謝謝你... – doesdos

0

使用follwoing正則表達式:"(.*),"

Regex rgx = new Regex("(.*),"); 
string s = "a,b,c,d"; 

Console.WriteLine(rgx.Match(s).Groups[1].Value); 
6

如果你想要的一切之前最後發生,用途:

int lastIndex = input.LastIndexOf(','); 
if (lastIndex == -1) 
{ 
    // Handle case with no commas 
} 
else 
{ 
    string beforeLastIndex = input.Substring(0, lastIndex); 
    ... 
} 
0

你還可以嘗試:

string s = "a,b,c,d"; 
string[] strArr = s.Split(','); 

Array.Resize(strArr, Math.Max(strArr.Length - 1, 1)) 

string truncatedS = string.join(",", strArr); 
相關問題