如何在C#中搜索String数组中的子字符串

时间:2013-12-30 18:28:47

标签: c# arrays substring

如何在String数组中搜索Substring?我需要在字符串数组中搜索一个Substring。字符串可以位于数组(元素)的任何部分或元素内。 (字符串的中间)我试过:Array.IndexOf(arrayStrings,searchItem)但是searchItem必须是在arrayStrings中找到的精确匹配。在我的例子中,searchItem是arrayStrings中完整元素的一部分。

string [] arrayStrings = {
   "Welcome to SanJose",
   "Welcome to San Fancisco","Welcome to New York", 
   "Welcome to Orlando", "Welcome to San Martin",
   "This string has Welcome to San in the middle of it" 
};
lineVar = "Welcome to San"
int index1 = 
   Array.IndexOf(arrayStrings, lineVar, 0, arrayStrings.Length);
// index1 mostly has a value of -1; string not found

我需要检查arrayStrings中是否存在lineVar变量。 lineVar可以有不同的长度和值。

在数组字符串中查找此子字符串的最佳方法是什么?

4 个答案:

答案 0 :(得分:11)

如果您需要的是关于数组中任何字符串中是否存在lineVar的bool true / false答案,请使用:

 arrayStrings.Any(s => s.Contains(lineVar));

如果你需要一个索引,这有点棘手,因为它可能出现在数组的多个项目中。如果你不是在寻找一个博尔,你能解释一下你需要什么吗?

答案 1 :(得分:1)

旧学校:

int index = -1;

for(int i = 0; i < arrayStrings.Length; i++){
   if(arrayStrings[i].Contains(lineVar)){
      index = i;
      break;
   }
}

如果您需要所有索引:

List<Tuple<int, int>> indexes = new List<Tuple<int, int>>();

for(int i = 0; i < arrayStrings.Length; i++){
   int index = arrayStrings[i].IndexOf(lineVar);
   if(index != -1)
     indexes.Add(new Tuple<int, int>(i, index)); //where "i" is the index of the string, while "index" is the index of the substring
}

答案 2 :(得分:0)

如果你需要包含数组元素中子字符串的第一个元素的索引,你可以这样做......

int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.

如果您需要包含子字符串的元素值,只需使用您刚刚获得的索引的数组,就像这样......

string fullString = arrayStrings[index];
  

注意:上面的代码会找到匹配的第一个匹配项。同样的,你   如果你想要数组中的最后一个元素,可以使用Array.FindLastIndex()方法   包含子字符串。

您需要将数组转换为List<string>,然后使用ForEach扩展方法和Lambda表达式来获取包含子字符串的每个元素。

答案 3 :(得分:0)

要使用C#在String数组中查找子字符串

    List<string> searchitem = new List<string>();
    string[] arrayStrings = {
       "Welcome to SanJose",
       "Welcome to San Fancisco","Welcome to New York",
       "Welcome to Orlando", "Welcome to San Martin",
       "This string has Welcome to San in the middle of it"
    };
   string searchkey = "Welcome to San";
   for (int i = 0; i < arrayStrings.Length; i++)
   {
    if (arrayStrings[i].Contains(searchkey))//checking whether the searchkey contains in the string array
    {
     searchitem.Add(arrayStrings[i]);//adding the matching item to the list 
    }
   string searchresult = string.Join(Environment.NewLine, searchitem);

搜索结果的输出:

欢迎来到SanJose

欢迎来到San Fancisco

欢迎来到圣马丁岛

此字符串的中间有“欢迎来到San”

相关问题