Animesh D
Animesh D

Reputation: 5002

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?

Upvotes: 2

Views: 230

Answers (3)

Oded
Oded

Reputation: 498962

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

Upvotes: 3

Abdul Munim
Abdul Munim

Reputation: 19217

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

Upvotes: 1

chess007
chess007

Reputation: 924

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

Upvotes: 2

Related Questions