从 c# 字符串中提取数字的方法有五种:正则表达式、循环和 char.isdigit()、int.tryparse()、string.split() 和 int.parse()、linq。
如何从 C# 字符串中提取数字
从 C# 字符串中提取数字可以通过以下几种方法实现:
1. 正则表达式
string input = "a1b2c3"; Regex regex = new Regex(@"\d+"); string result = regex.Match(input).Value;
2. 循环和 Char.IsDigit()
string input = "a1b2c3"; string result = ""; foreach (char c in input) { if (Char.IsDigit(c)) { result += c; } }
3. int.TryParse()
此方法将尝试将字符串转换为整数,如果成功则返回 true,否则返回 false。
string input = "123"; int result; bool success = int.TryParse(input, out result);
4. String.Split() 和 int.Parse()
string input = "1,2,3"; string[] numbers = input.Split(','); int[] results = new int[numbers.Length]; for (int i = 0; i <p><strong>5. LINQ</strong></p><pre class="brush:php;toolbar:false">string input = "a1b2c3"; int[] results = input.Where(c => Char.IsDigit(c)).Select(c => (int)char.GetNumericValue(c)).ToArray();
根据具体需求,选择最合适的方法即可。