简体   繁体   中英

Search a string for a specific character

So I am doing homework and I am stuck on one spot. I have to write a calculator that takes 2 numbers and either +, -, *, / or % and then it will do the appropriate math. I got the numbers part and the error checking for that down, but the characters part is messing me up. I have tried IndexOf and IndexOfAny and it says there is no overload method that contains 5 arguments. I got a similar response from Contains.

Here is what I have, please help! Thank you so much for any assistance you can offer!

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 takes char[], not char params, so you write:

inputValue.IndexOfAny(new char[] {'a', 'b', 'c'})

you can do

if (new []{"+" , "-" , "*" , "/" , "%"}.Any(i => inputValue.IndexOf(i) >= 0))
{
    ....
}

or

if (inputValue.IndexOfAny(new[] {'+' , '-' , '*' , '/' , '%'}) >= 0)
{
     ....
}
    int index = inputValue.IndexOfAny(new char[] {'+' , '-' , '*' , '/' , '%'});
    if (index != -1)
    {
        modifier = inputValue[index];
        goto DoMath;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM