【问题标题】:C# String Array ContainsC# 字符串数组包含
【发布时间】:2017-07-05 04:20:08
【问题描述】:

有人可以向我解释为什么代码的顶部可以工作,但是当 test 是一个数组时却不行?

string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}

下面的代码不起作用

string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}

【问题讨论】:

  • 这两种类型 - stringstring[] - 是不同的,所以每个类型的 .Contains 方法是不同的方法,即使它具有相同的名称,并且每个方法都执行不同的操作.

标签: c# arrays contains


【解决方案1】:

在第一种情况下,您调用String.Contains 检查字符串是否包含子字符串。
所以,这个条件返回true

在第二种情况下,您在 string[] 上调用 Enumerable.Contains,它会检查字符串数组是否包含特定值。
由于您的集合中没有"Customer" 字符串,因此它返回false

这是两个名称相似但实际上不同类型的不同方法。

如果要检查集合中是否有任何字符串包含“客户”作为子字符串,则可以使用LINQ .Any()

if (test.Any(s => s.Contains("Customer"))
{
    test[1] = "a";
}

【讨论】:

    【解决方案2】:

    第一个 sn-p 在另一个字符串 Customer - 中搜索字符串 Customer,但在第二个 sn-p 字符串 Customer 中搜索字符串数组,其中一个是 Customer -。因此第二个返回 false。

    这从你声明 test 的方式就很明显了

    string test = "Customer - ";
    

    string[] test = { "Customer - " };
    

    注意大括号。这就是您定义集合的方式(此处为数组)

    要使第二个 sn-p 工作,您应该这样做

    string[] test = { "Customer - " };
    if (test.Any(x => x.Contains("Customer")))
    {
        test[1] = "a";
    }
    

    【讨论】:

    • 谢谢,我认为第二个 sn-p 有点误导,因为它检查的是完全匹配而不是真正的包含。我的测试数组的值比我在这里所说的要多。如果是这样,我该如何检查索引?
    • 您需要从0array.length-1 运行一个普通的旧for 循环。当找到值时,循环值就是索引。除此之外,您可以使用 linq 来完成。 stackoverflow.com/a/10443540/1011959
    【解决方案3】:
    string test = "Customer - ";
    if (test.Contains("Customer"))
    {
      test = "a";
    }
    

    在此包含是一个字符串类方法,它是 IEnumerable 检查的基础

    “客户 -”拥有客户

    但是

    string[]test = { "Customer - " };
    if (test.Contains("Customer"))
    {
       test[1]= "a";
     }
    

    在这个地方包含一个 IEnumerable 方法,它是 IEnumerable 检查的基础。所以,你更改代码是行不通的

    string[] test = { "Customer - " };
    if (test.Any(x => x.Contains("Customer")))
    {
    
    }
    

    test[1]="a" 抛出异常是因为数组位置从 0 开始而不是 1

    【讨论】:

      【解决方案4】:

      因为在第二种情况下,当您在字符串数组中搜索第一个字符串时,您的 if 条件为假。您可以使用任何关键字搜索数组中与客户匹配的任何字符串,也可以搜索 test[0] 以搜索数组中的第一个字符串(如果它与客户匹配):

      if (test[0].Contains("Customer"))
          {
              //your rest of the code here
          }
      
      
       if (test.Any(x => x.Contains("Customer")))
          {
              //your rest of the code here
          }
      

      【讨论】:

      • 您不了解问题的上下文,因此,最终您给出的答案是不正确的。删除或编辑您的答案。
      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 2021-07-18
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      相关资源
      最近更新 更多