Tokenizer/Split in c#?

本文关键字:in Split Tokenizer | 更新日期: 2023-09-27 18:12:48

我正试图把它从java转到c#,除了标记器之外几乎已经完成了所有的工作。我知道你在c#中使用分割,但我似乎不明白。程序需要将用户输入的方程式(4/5 + 3/4)拆分为没有括号的格式。如果有任何帮助就太好了。

// read in values for object 3
Console.Write("Enter the expression (like 2/3 + 3/4 or 3 - 1/2): ");
string line = Console.ReadLine();
// Works with positives and neagative values!
// Split equation into first number/fraction, operator, second number/fraction
StringTokenizer st = new StringTokenizer(line, " ");
string first = st.nextToken();
char op = (st.nextToken()).charAt(0);
string second = st.nextToken();

稍后我将需要符号(+,-,*或/),并且需要检查它是否是一个整数,我在代码中紧接着这样做。下面是我尝试过的,但我被炭卡住了。

char delimeters = ' ';
string[] tokens = line.Split(delimeters);
string first = tokens[0];
char c = tokens[1]

Tokenizer/Split in c#?

tokens是字符串数组,所以token[1]是字符串,不能将字符串赋值给char。这就是javacode中写charAt(0)的原因。将其转换为c#得到

char delimeters = ' ';
string[] tokens = line.Split(delimeters);
string first = tokens[0];
char c = tokens[1][0];

相当于Java的

String first = st.nextToken();
char op = (st.nextToken()).charAt(0);
String second = st.nextToken();

string first = tokens[0];
char c = tokens[1][0];
string second = tokens[2];

很可能需要在循环中执行此操作。first将被读取一次,然后在有更多数据可用时读取operatoroperand,如下所示:

List<string> operands = new List<string> {tokens[0]};
List<char> operators = new List<char>();
for (int i = 1 ; i+1 < tokens.Length ; i += 2) {
    operators.Add(tokens[i][0]);
    operands.Add(tokens[i+1]);
}

在此循环之后,operators将包含表示操作符的N字符,operands将包含表示操作数的N+1字符串。

我只是编码这个(即我没有尝试)…

//you should end up with the following
// tokens[0] is the first value, 2/3 or 3 in your example
// tokens[1] is the operation, + or - in your example
// tokens[2] is the second value, 3/4 or 1/2 in your example
char delimeters = ' ';
string[] tokens = line.Split(delimeters);

char fractionDelimiter = '/';
// get the first operand
string first = tokens[0];
bool result = int.TryParse(first, out whole);
double operand1 = 0;
//if this is a fraction we have more work...
// we need to split again on the '/'
if (result) {
   operand1 = (double)whole;
} else {
   //make an assumption that this is a fraction
   string fractionParts = first.Split(fractionDelimiter);
   string numerator = fractionParts[0];
   string denominator = fractionParts[1];
   operand1 = int.Parse(numerator) / int.Parse(denominator);
}
// get the second operand
string second = tokens[2];
bool secondResult = int.TryParse(second, out secondWhole);
double operand2 = 0;
if (secondResult) {
   operand2 = (double)secondWhole;
} else {
   //make an assumption that this is a fraction
   string secondFractionParts = second.Split(fractionDelimiter);
   string secondNumerator= secondFractionParts[0];
   string secondDenominator = secondFractionParts[1];
   operand2 = int.Parse(secondNumerator) / int.Parse(secondDenominator);
}

剩下的应该很简单,找出操作是什么,并对operand1和operand2进行操作