从数组和引用数组中搜索字符串

时间:2014-07-27 02:45:01

标签: c# arrays

我是C#的新手,我正在尝试搜索字符串以查看它是否包含字符串数组的成员。如果字符串确实包含数组中的某些内容,那么我想记录它找到的数组成员的索引号,然后显示它。

string stringToBeSearched = "I want to find item2 or item6";
string[] array = { "item1", "item2", "item3" };
// Search stringToBeSearched for anything in array, then enter the array 
// member's index value into int position
int position = //array index number of item found
Console.WriteLine("{0} was found.", array[position]);
Console.ReadLine();

3 个答案:

答案 0 :(得分:1)

您可以使用stringToBeSearched将每个数组元素与IndexOf进行比较。

string stringToBeSearched = "I want to find item2 or item6";
string[] array = {"item1", "item2", "item3"};

int position;

for (int i = 0; i < array.Length; i++) {
    string str = array[i];

    if (stringToBeSearched.IndexOf(str) >= 0) {
        position = i;
        Console.WriteLine("{0} was found.", str);
        Console.ReadLine();
    }
}

// Result: 
// item2 was found.

答案 1 :(得分:1)

使用Linq和Generics的方法

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main(String[] args)
    {
       string[] array1 = "I want to find item2 or item6".Split(' ');
       string[] array2 = {"item1", "item2", "item6"};

       IEnumerable<string> results = array1.Intersect(array2,
                                                     StringComparer.OrdinalIgnoreCase);

       foreach (string s in results)
          Console.WriteLine("{0} was found at index {1}.", 
                            s, 
                            Array.IndexOf(array2, s));

    }
}

答案 2 :(得分:0)

string stringToBeSearched = "I want to find item2 or item6";
string[] array = { "item1", "item2", "item3" };

string firstOrDefault = array.FirstOrDefault(stringToBeSearched.Contains);
int position = firstOrDefault == null
   ? -1
   : Array.IndexOf(array, firstOrDefault);

if (position >= 0)
   Console.WriteLine("{0} was found.", array[position]);
else
   Console.WriteLine("Did not find any of the strings.");

Console.ReadLine();

请注意,这将找到第一个匹配的字符串。如果不止一个,你就不会知道其他人。