1

我正在尝试将其从 java 转换为 C#,并且除了分词器之外几乎已经完成了所有工作。我知道您在 C# 中使用 split 但我似乎无法弄清楚。程序需要拆分用户输入的方程(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]
4

3 回答 3

2

tokens是一个字符串数组,所以 token[1] 是一个字符串,你不能将一个字符串分配给一个 char。这就是为什么在 javacode 中编写charAt(0). 将其转换为 C# 给出

char delimeters = ' ';
string[] tokens = line.Split(delimeters);
string first = tokens[0];
char c = tokens[1][0];
于 2013-05-08T00:56:45.920 回答
1

相当于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表示操作数的字符串。

于 2013-05-08T00:56:58.637 回答
0

我只是对此进行了编码(即我没有尝试过)......但是你去吧。

//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);
}

其余的应该像找出操作是什么并使用操作数 1 和操作数 2 一样简单

于 2013-05-08T01:17:51.763 回答