[英]Checking if string contains one of the array values using C# .net
我有string[] srt={"t","n","m"}
我需要知道用戶輸入是否包含str中的值之一並打印該值
我嘗試使用此代碼,但不適用於我
string str = Textbox.Text; string s = ""; string[] a = {"m","t","n"}; if (str.Contains(a.ToString())) { s = s + a; } else { s = s + "there is no match in the string"; } Label1.Text = s;
您需要在數組中搜索str中具有的字符串值,因此
if (str.Contains(a.ToString()))
將會
if(a.Contains(s))
您的代碼將是
if (a.Contains(str))
{
s = s + "," + a;
}
else
{
s = s + "there is no match in the string";
}
Label1.Text = s;
另外要注意的是,您應使用含義全名,而不是a
, s
。
您還可以使用條件運算符?:使其更簡單。
string matchResult = a.Contains(s) ? "found" : "not found"
不需要將數組轉換為字符串。 如果您不關心匹配哪個字符,請使用Any()
var s = a.Any(anA => str.Contains(anA))
? "There is a match"
: "There is no match in the string";
如果您想要匹配項:
var matches = a.Where(anA => str.Contains(anA));
var s = matches.Any()
? "These Match: " + string.Join(",", matches)
: "There is no match in the string";
請參見檢查字符串數組是否包含值,如果包含,則獲取其位置。可以使用Array.IndexOf方法:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.