使用 ‘||’ 逻辑或运算符来比较字符串

huangapple go评论168阅读模式
英文:

Using a '||' logical OR operator for comparing strings

问题

我写了一个简单的条件语句,其中我从用户那里获取一个字符串输入,检查它是否等于某个值,但我的代码的性质使我需要在两个字符串之间添加一个额外的操作数。

我尝试了这个,但它会报错,因为你不能在两个字符串之间进行操作,显然存在某种逻辑错误,但我想要一个类似的解决方案来解决这个问题。

if (Console.ReadLine() == ("s"||"S"))

现在我知道如果我创建一个单独的变量并仅使用它来检查"s"和"S",那么这将起作用,但我想在同一语句内联并在单个语句内完成。如果有办法在这一行内让它工作,请告诉我。

英文:

I have written a simple conditional statement, in which I'm getting a string input from the user, checking if it's equal to something but the nature of my code makes me add a single more operand to operate between

I tried this but it gives an error that you can't operate between two strings, obv there is some logical fallacy but I want a similar solution to this problem

if (Console.ReadLine() == ("s"||"S"))

Now I know this works if I make a separate variable and just check with it for both "S" and "s", but I want to do it inline and within that single statement, If I add another "Readline()" it will just take two inputs and won't do what I want it to do.

If there is anyway to make this work within that line, please let me know.

答案1

得分: 1

You have to declare the variable outside the condition, but you can do everything else in one line.

You can use is to make it slightly more readable (but only works for literal comparison).

string input;
if ((input = Console.ReadLine()) is "s" or "S")

Or if you have to use == then

string input;
if ((input = Console.ReadLine()) == "s" || input == "S")

Would I suggest doing this? No. Do the sane thing by not cramming all this logic in one line.

string input = Console.ReadLine();
if (input is "s" or "S")
英文:

You have to declare the variable outside the condition, but you can do everything else in one line.

You can use is to make it slightly more readable (but only works for literal comparison).

string input;
if ((input = Console.ReadLine()) is "s" or "S")

Or if you have to use == then

string input;
if ((input = Console.ReadLine()) == "s" || input == "S")

Would I suggest doing this? No. Do the sane thing by not cramming all this logic in one line.

string input = Console.ReadLine();
if (input is "s" or "S")

答案2

得分: -2

if (Console.ReadLine().ToLower() == "s")

英文:

What about trying

if (Console.ReadLine().ToLower() == "s")

huangapple
  • 本文由 发表于 2023年2月8日 12:56:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定