简体   繁体   中英

Matching a string against an array of strings

I have an array of four operations which I want to match against an input string.

My attempt:

string[] operations = {"add","sub","mul","div"};
string rawInput = Console.ReadLine();
string[] inputs = rawInput.Split(delims,StringSplitOptions.RemoveEmptyEntries);
firstInput = inputs[0].Trim();

foreach (string operation in operations) 
{
    if (firstInput.Contains(operation))
        Console.WriteLine("Valid operation: {0}",operation);
}

As I expected, this prints Valid operation if I input add, sub, mul or div.

To print a message for invalid input, I have included an else condition like this:

else
{
    Console.WriteLine("Invalid operation: {0}", firstInput);
    break;
}

If I input sub now, I get:

Invalid operation: sub

If I remove the break statement and input sub :

Invalid operation: sub
Valid operation: sub
Invalid operation: sub
Invalid operation: sub

How do I modify the logic so that I get correct messages and only once?

Look if the first input is in your list of valid operations, instead of the other way around (using LINQ):

if (operations.Contains(firstInput))
{
  Console.WriteLine("Valid operation: {0}", firstInput);
}
else
{
  Console.WriteLine("Invalid operation: {0}", firstInput);
}

If iterating over the list, as you have done, this is one option:

bool foundValidOP = false;
foreach (string operation in operations) 
{
    if (firstInput.Equals(operation, StringComparison.InvariantCultureIgnoreCase))
    {
        foundValidOP = true;
        break;
    }
}

if (foundValidOP)
{
  Console.WriteLine("Valid operation: {0}", firstInput);
}
else
{
  Console.WriteLine("Invalid operation: {0}", firstInput);
}

Your foreach loop iterates over each of the entries in operations , so your logic is incorrect because it will break out of the loop if the input doesn't match the first element in operations (namely, "add" ). You really want to break out of the loop if a valid operation is found and otherwise keep scanning. Here is some sample code:

bool validOperation = false;
foreach (string operation in operations) 
{
    if (firstInput.Contains(operation))
    {
        Console.WriteLine("Valid operation: {0}",operation);
        validOperation = true;
        break;
    }
}
if (!validOperation)
{
    Console.WriteLine("Invalid operation: {0}", firstInput);
}

You can try this:

string[] operations = { "add", "sub", "mul", "div" };
var firstInput = "sudb";

var x = operations.SingleOrDefault(o => o == firstInput);

if (x != null)
    Console.WriteLine("Valid:" + x);
else
    Console.WriteLine("Invalid:" + firstInput);

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