在字符串中搜索特定字符
本文关键字:字符 搜索 字符串 | 更新日期: 2023-09-27 17:59:03
所以我在做作业,我被困在一个地方。我必须写一个计算器,它取2个数字和+,-,*,/或%,然后它会做适当的数学运算。我记下了数字部分和错误检查,但字符部分把我搞砸了。我试过IndexOf和IndexOfAny,它说没有包含5个参数的重载方法。Contains也给了我类似的回复。
这是我的东西,请帮忙!非常感谢您提供的任何帮助!
Console.Write("'r'nPlease enter either +, -, * or / to do the math.'r'n");
ReadModifier:
inputValue = Console.ReadLine();
if (inputValue.IndexOfAny("+" , "-" , "*" , "/" , "%"))
{
modifier = Convert.ToChar(inputValue);
goto DoMath;
}
else
{
Console.Write("'r'nPlease enter either +, -, * or / to do the math.'r'n");
goto ReadModifier;
}
IndexOfAny采用char[],而不是char-params,因此您可以编写:
inputValue.IndexOfAny(new char[] {'a', 'b', 'c'})
int index = inputValue.IndexOfAny(new char[] {'+' , '-' , '*' , '/' , '%'});
if (index != -1)
{
modifier = inputValue[index];
goto DoMath;
}
您可以进行
if (new []{"+" , "-" , "*" , "/" , "%"}.Any(i => inputValue.IndexOf(i) >= 0))
{
....
}
或
if (inputValue.IndexOfAny(new[] {'+' , '-' , '*' , '/' , '%'}) >= 0)
{
....
}