Bobbyman5506
Bobbyman5506

Reputation: 11

How to find the first instance of more than 1 character(s) in a string

I am looking to see if there is a better way to figure out if which of two characters appears first in a string.

my current code for this is

string UserInput = Console.Readline;
char FirstFound;

if (UserInput.IndexOf('+') > UserInput.IndexOf('-') )
{
    FirstFound = '+';
}
else
{
    FirstFound = '-';
}

Is there a method that allows more than 1 input so can simplify this? Or anything else to make this shorter?

Upvotes: 1

Views: 579

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415810

You can shorten it a little bit by understanding the code effectively has the - character as the default value, because it's the result of the else block. With that in mind, we can do this to remove the else block:

string UserInput = Console.Readline();
char FirstFound = '-';

if (UserInput.IndexOf('+') > UserInput.IndexOf('-') )
{
    FirstFound = '+';
}

We could also do this, which is not shorter but will perform better:

string UserInput = Console.ReadLine();
char FirstFound;
foreach(char c in UserInput)
{
    if (c == '+' || c == '-')
    {
        FirstFound = c;
        break;
    }
}

Which we can shorten to use the linq FirstOrDefault() method:

string UserInput = Console.ReadLine();
char FirstFound = UserInput.FirstOrDefault(c => "-+".Contains(c));

If you want to able to expand this to allow more than two search targets, you can add the targets to the string like so, with no additional lines of code:

string UserInput = Console.ReadLine();
char FirstFound = UserInput.FirstOrDefault(c => "-+*/x÷".Contains(c));

Upvotes: 5

Related Questions