[英]operators in C#
我有一個單詞數組,我想刪除所有與模式匹配的單詞,並且還刪除每個少於3個字符的單詞。 以下代碼是否可以完成我的想法? 提前致謝。
foreach (Match mtch in mc )
{
string p = @"[A-Z,a-z,0-9]" ;
if (Regex.IsMatch(mtch.Value, p) || mtch.Length < 3 )
{
continue;
}
else
{
filter.Add(mtch.Value);
}
}
因為我真的對使用||感到困惑 運營商。
|| (或運算符)以以下方式工作。 如果條件1返回true,而條件2返回false,則總結果為true。
true || true = true
true || false = true
false || true = true
flase || false = false
在您的情況下:
if (Regex.IsMatch(mtch.Value, p) || mtch.Length < 3 )
它正在檢查mtch的值是否匹配RegEx或mtch的長度小於3,然后繼續執行循環。 現在,這里有兩個條件,如果兩個條件的結果均為假,則這僅會進入if語句的else部分。 即mtch的值與正則表達式p不匹配,並且mtch的值大於或等於3
|| 運算符執行邏輯或。
它將首先計算左操作數,如果為true,則表達式為true。 如果左操作數為false,則將評估第二個操作數。
如果將以下示例作為控制台應用程序運行,將看到發生的情況:
using System;
namespace OrOperand
{
class Program
{
static void Main(string[] args)
{
DisplayResult(true, true);
DisplayResult(true, false);
DisplayResult(false, true);
DisplayResult(false, false);
}
private static void DisplayResult(bool left, bool right)
{
_left = left;
_right = right;
Console.WriteLine("Running " + left + " || " + right);
if (Left() || Right())
{
Console.WriteLine(_left + " || " + _right + " is true");
}
else
{
Console.WriteLine(_left + " || " + _right + " is false");
}
}
static bool _left = true;
static bool _right = false;
static bool Left()
{
Console.WriteLine("Left called");
return _left;
}
static bool Right()
{
Console.WriteLine("Right called");
return _right;
}
}
}
這將輸出:
Running True || True
Left called
True || True is true
Running True || False
Left called
True || False is true
Running False || True
Left called
Right called
False || True is true
Running False || False
Left called
Right called
False || False is false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.