我正在尝试将其从java转换为C#并且除了tokenizer之外几乎完成了所有这些操作。我知道你在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();
我稍后需要symobol(+, - ,*或/),并且需要检查它是否是我在我的代码中执行的整数。下面是我尝试的一种,但我坚持使用char。
char delimeters = ' ';
string[] tokens = line.Split(delimeters);
string first = tokens[0];
char c = tokens[1]
答案 0 :(得分: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];
答案 1 :(得分: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
将被阅读一次,然后您会在有更多数据的情况下阅读operator
和operand
,如下所示:
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
个字符串。
答案 2 :(得分: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);
}
其余的应该像找出操作是什么一样简单,并使用operand1和operand2进行操作