我应该如何在字符串中搜索一系列字符,例如 "x*y"?



我正在尝试使用数学克莱默定理制作一个确定计算器,如您所见,我将定理转换为代码convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1));一切都很好,直到我需要计算 2 个未知数字,我不知道如何在代码中"告诉"x + x = 2x3y-y = 2y的计算机, 所以我坚持如果我将 Crammer 方程转换为字符串,我可以找到所有匹配项,例如x + xy + 2yy * y并从中开始一个可以解决我初始问题的解决方案,就像如果我找到一个x * x模式,我会通过 if 语句或其他东西告诉 pc 模式x * xx^2的。 话虽如此,我想找出字符串中存在的特定序列(如X * yy + x(的数量,我确实尝试了一些foreach循环和for循环,但我无法让它工作,我不知道接下来应该如何处理这个问题,plase 帮助。

这是我的代码:

using System;
using InputMath;
namespace MathWizard
{
class Determinants
{
//Determinant of a first point and a second graphical point on the xoy axis.
public static void BasicDeterminant()
{
float x;
float y;
float x1 = Input.x1;
float y1 = Input.y1;
float x2 = Input.x2;
float y2 = Input.y2;
float result;
string convertedString;
string pointsValue;
string[] point;
Console.WriteLine("Please introduce the 2 graphical points ( A and B) n in the order x1 y1 x2 y2, separated by a space ");
pointsValue = Console.ReadLine();
point = pointsValue.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

x1 = Convert.ToInt32(point[0]);
y1 = Convert.ToInt32(point[1]);
x2 = Convert.ToInt32(point[2]);
y2 = Convert.ToInt32(point[3]);

//The Cramer's Rule for solving a 2 points determinant ( P1(x1,y1) and P2(x2,y2)
convertedString = Convert.ToString (x * y1 * 1 + x1 * y2 * 1 + x2 * x * y - (1 * y1 * x2 + 1 * y2 * y + 1 * y * x1));
}
}
}

您还可以使用以下regex,它将找到每个运算符不区分大小写的 x*y:

string pattern = /(x(*|+|-|/|^)y)/gi;

然后你可以做一些string.Contains(pattern);检查。 让我知道这是否有帮助。

编辑:更新的模式

更新了模式,以便它也允许y9X10等变量。 任何单个字符(x 或 y(后跟任意数量的数字。

string pattern =/(xd*(*|+|-|/|^)yd*)/gi; // could match X1*y9

这不考虑空格,因此您可以使用一些.replace()来摆脱空格或使用.split(/s/)并在使用此模式之前获取没有空格的字符串数组。

bool found = false;
int xyCount = 0;
if(convertedString.Contains("X*Y")){
found = true;
xyCount++;
//makes a substring without the first case of the "X*Y"
string s = convertedString.SubString(convertedString.IndexOf("X*Y"))
if(s.Contains("X*Y")){
xyCount++;
}

这可能不是最好的方法,但你可以做出更好的方法做这样的事情

相关内容

最新更新