2014-01-29 23 views
-7

的一部分,我有具有以下格式的字符串:C#只讀整串

"####/xxxxx" 

前的文本「/」始終是一個整數,我需要閱讀它。我怎樣才能得到這個字符串的整數部分(在「/」之前)?

謝謝你的幫助。

+3

你有什麼試過的?你看過字符串實例上可用的方法嗎? – Magus

+1

使用String.Split來獲取零件和Convert.ToInt32以獲取數字。或者使用SO搜索/ Google ... –

回答

4

可以在/分割字符串,然後使用int.TryParse陣列的第一元件上,以查看它是否像的整數:

string str = "1234/xxxxx"; 
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries); 
int number = 0; 
if (str.Length == 2 && int.TryParse(array[0], out number)) 
{ 
    //parsing successful. 
} 
else 
{ 
    //invalid number/string 
} 

Console.WriteLine(number); 
1

使用IndexOfSubstring

int indexOfSlash = text.IndexOf('/'); 
string beforeSlash = null; 
int numBeforeSlash = int.MinValue; 
if(indexOfSlash >= 0) 
{ 
    beforeSlash = text.Substring(0, indexOfSlash); 
    if(int.TryParse(beforeSlash, out numBeforeSlash)) 
    { 
     // numBeforeSlash contains the real number 
    } 
} 
0

另一個替代方案:使用正則表達式:

var re = new System.Text.RegularExpression(@"^(\d+)/", RegexOptions.Compiled); 
// ideally make re a static member so it only has to be compiled once 

var m = re.Match(text); 
if (m.IsMatch) { 
    var beforeSlash = Integer.Parse(re.Groups[0].Value); 
}