【问题标题】:Checking if string contains one of the array values using C# .net使用 C# .net 检查字符串是否包含数组值之一
【发布时间】:2015-04-17 18:27:40
【问题描述】:

我有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;

【问题讨论】:

标签: c# asp.net .net arrays


【解决方案1】:

你需要在数组中搜索你在 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;

作为附加说明,您应该使用有意义的全名而不是as

您还可以使用条件operator ?: 使其更简单。

string matchResult = a.Contains(s) ? "found" : "not found"

【讨论】:

    【解决方案2】:

    不需要将数组转换为字符串。如果您不在乎匹配哪个字符,请使用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";
    

    【讨论】:

      【解决方案3】:

      Checking if a string array contains a value, and if so, getting its position 您可以使用 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
      }
      

      【讨论】:

        猜你喜欢
        • 2016-06-07
        • 1970-01-01
        • 1970-01-01
        • 2011-02-24
        • 2015-02-07
        • 2012-05-06
        • 1970-01-01
        • 2012-08-11
        • 1970-01-01
        相关资源
        最近更新 更多