c# - 分离 int 和 char 并生成整数

标签 c#

我写了一个简单的程序,将参数中的字符串拆分为数字、字母和运算符,但是我遇到了 23x+3=8

foreach (char x in args[i]){

    if (char.IsNumber(x)){
        inter[i] = Convert.ToInt32(x);
            Console.WriteLine("{0} is a number ", x);
    }
    else if (char.IsLetter(x)){
        apha[i] = x;
        Console.WriteLine("{0} is a Letter ", x);
    }
    else if (char.IsSymbol(x)){
        symbol[i] = x;
        Console.WriteLine("{0} is a Symbol ", x);
    }

我发现输出分为每个字符 2 和 3 我想要 23 作为一个整数。有没有办法把 2 个数字放在一起?

最佳答案

我会尝试以下方法

string equation = "25x+20=120";

// Guard against an empty input
if (String.IsNullOrWhiteSpace(equation))
    throw new ArgumentException("No equation given!");

// Regex split
// Split is being applied on the mathematical operations
var result = Regex.Split(equation, @"([*+-/=])");
foreach (var item in result)
{
    Console.WriteLine(item);
    // TODO : Further operations
}

这将生成输出

25x
+
20
=
120

该过程使用正则表达式。 ([*+-/=]) 将拆分指定的数学运算,() 将确保运算包含在结果拆分中,从而允许您重建操作树。

请参阅 System.Text.RegularExpressions 上的文档,您可以在 Regular Expression Language Reference 上看到更深入的引用。

关于c# - 分离 int 和 char 并生成整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997870/

相关文章:

c# - 通用类型参数协变和多接口(interface)实现

c# - 使用反射查找实现的接口(interface)

c# - 匹配文件路径字符串的第一部分

c# - GetWindowRect 在一个应用程序上返回错误值,所有其他应用程序都是正确的

c# - 有没有办法从 azure blob 中获取所有文件

c# - iOS Safari 上的浏览​​器 session 之间未保存 Cookie

c# - 如何通过单击标签在 Xamarin.Forms 中调用电话?

c# - OLEDBConnection.Open() 生成 'Unspecified error'

c# - 使用 LINQ 计算特定列的总和

c# - Linq group by parent 属性 order by child