-
慕容3067478
有几种方法可以做到这一点,例如 Regex 和 Linq。对于短字符串,您可以使用 Linq,例如:public static void Main(){ var myStringValue = "burger 5$"; var numbersArray = myStringValue.ToArray().Where(x => char.IsDigit(x)); foreach (var number in numbersArray) { Console.WriteLine(numbersArray); }}
-
catspeake
如果您查看Regex.Split,数字文章。你会在那里找到答案。修改后的代码可能看起来像var source = new List<string> { "burger 5$", "pizza 6$", "roll 1$ and salami 2$"};var result = new List<int>();foreach (var input in source){ var numbers = Regex.Split(input, @"\D+"); foreach (string number in numbers) { if (Int32.TryParse(number, out int value)) { result.Add(value); } }}希望能帮助到你。彼得
-
富国沪深
您可以查看并使用此代码解决问题: List<string> word_number = new List<string>(); List<int> number = new List<int>(); word_number.Add("burger 5$"); word_number.Add("hamburger 6$"); word_number.Add("burger 12$"); foreach (var item in word_number) { string[] parts = item.Split(' '); string[] string_number = parts[1].Split('$'); number.Add(Convert.ToInt16(string_number[0])); Console.WriteLine(string_number[0]); }
-
白衣染霜花
使用linq和Regex:List<string> list = new List<string>(){"burger 5$","ab12c","12sc34","sd3d5"};Regex nonDigits = new Regex(@"[^\d]"); List<string> list2 = list.Select(l => nonDigits.Replace(l, "")).ToList();