Q
C#只讀整串
-7
A
回答
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
使用IndexOf
和Substring
:
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);
}
相關問題
- 1. C++ ifstream的只讀整數
- 2. C++字符串類是隻讀的嗎?
- 3. C#只讀串行端口數據來
- 4. 只讀在C#
- 5. sqlite調整隻讀表
- 6. 整個模型爲只讀
- 7. C++打開只讀
- 8. 當我讀取整數後,C無法讀取字符串
- 9. 閱讀整個字符串
- 10. 如何從字符串,空格,新行和整數中的文件中只讀取整數C
- 11. C++ cin正整數只有
- 12. MongoDb C#只讀字段
- 13. Objective C只讀int?什麼?
- 14. 開放SQLITE只讀在C#
- 15. 只讀在C#VS在VB.NET
- 16. 只讀角色c#mvc
- 17. 只讀屬性,在C#6.0
- 18. C#SqlDataReader只讀取1行
- 19. asp.net,c#.net只讀字段
- 20. Objective-C - 只讀NSMutableArray和NSCoding?
- 21. C#的BindingList只讀錯誤
- 22. C++錯誤:只讀變量
- 23. C#make文件從只讀中讀取
- 24. 閱讀整數用C
- 25. 閱讀整數,在C++
- 26. 閱讀整數矩陣(C++)
- 27. C++:getline()讀完整行嗎?
- 28. QtableView將整行設置爲只讀
- 29. Python整數到只讀緩衝區
- 30. 如何使整個jqGrid禁用/只讀
你有什麼試過的?你看過字符串實例上可用的方法嗎? – Magus
使用String.Split來獲取零件和Convert.ToInt32以獲取數字。或者使用SO搜索/ Google ... –