C#-8+54-2怎么将符号与数字分别插入string类型列表和double类型列表
时间: 2024-04-14 16:29:33 浏览: 21
要将符号和数字分别插入到 `string` 类型的列表和 `double` 类型的列表中,你可以稍微修改上面的代码。在遍历匹配结果时,将符号添加到 `string` 类型的列表中,将数字解析为 `double` 类型后添加到另一个列表中。
下面是修改后的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "C#-8+54-2";
List<string> symbols = new List<string>();
List<double> numbers = new List<double>();
Regex regex = new Regex(@"([-+])|(\d+)");
MatchCollection matches = regex.Matches(input);
foreach (Match match in matches)
{
if (match.Groups[1].Success)
{
symbols.Add(match.Groups[1].Value);
}
else if (match.Groups[2].Success)
{
numbers.Add(double.Parse(match.Groups[2].Value));
}
}
Console.WriteLine("Symbols: " + string.Join(", ", symbols));
Console.WriteLine("Numbers: " + string.Join(", ", numbers));
}
}
```
输出结果为:
```
Symbols: -, +
Numbers: 8, 54, 2
```
现在,符号被插入到 `symbols` 列表中,而数字被解析为 `double` 类型后插入到 `numbers` 列表中。