如何在C#中的字符串数组中搜索子字符串 [英] How to search a Substring in String array in C#

查看:936
本文介绍了如何在C#中的字符串数组中搜索子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在字符串数组中搜索子字符串?我需要在字符串数组中搜索子字符串.字符串可以位于数组(元素)的任何部分或元素内. (字符串的中间)我已经尝试了:Array.IndexOf(arrayStrings,searchItem),但是searchItem必须与在arrayStrings中找到的完全匹配.在我的情况下,searchItem是arrayStrings中完整元素的一部分.

How to search for a Substring in String array? I need to search for a Substring in the string array. The string can be located in any part of the array (element) or within an element. (middle of a string) I have tried : Array.IndexOf(arrayStrings,searchItem) but searchItem has to be the EXACT match to be found in arrayStrings. In my case searchItem is a portion of a complete element in 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的长度和值可以不同.

I need to check whether lineVar variable is present in arrayStrings. lineVar can be of different length and value.

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

What would be the best way to find this substring within an array string?

推荐答案

如果您需要的是关于lineVar是否存在于数组的任何字符串中的布尔型真/假答案,请使用以下方法:

If all you need is a bool true/false answer as to whether the lineVar exists in any of the strings in the array, use this:

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

如果您需要索引,那会有点棘手,因为它可以出现在数组的多个项目中.如果您不想要布尔,可以解释您的需求吗?

If you need an index, that's a bit trickier, as it can occur in multiple items of the array. If you aren't looking for a bool, can you explain what you need?

这篇关于如何在C#中的字符串数组中搜索子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆