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

5

如何在字符串数组中搜索子字符串?我需要在字符串数组中搜索子字符串。该字符串可以位于数组的任何部分(元素)或元素内部(字符串中间)。我已经尝试过: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个回答

13
如果你只需要一个布尔 True/False 答案,以判断 lineVar 是否存在于数组中的任何字符串中,请使用以下代码:
 arrayStrings.Any(s => s.Contains(lineVar));
如果您需要一个索引,那就有点棘手了,因为它可能出现在数组的多个项中。如果您不是在寻找一个布尔值,那么您可以解释一下您需要什么吗?

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


2

传统做法:

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
}

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,然后使用ForEach扩展方法以及Lambda表达式来获取包含子字符串的每个元素。

0

使用C#查找字符串数组中的子字符串

    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);

搜索结果输出:

欢迎来到圣何塞

欢迎来到旧金山

欢迎来到圣马丁

这个字符串中间有“欢迎来到圣”的字样


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接