簡體   English   中英

如何在 C# 中的字符串數組中搜索子字符串

[英]How to search a Substring in String array in C#

如何在字符串數組中搜索子字符串? 我需要在字符串數組中搜索一個子字符串。 字符串可以位於數組(元素)的任何部分或元素內。 (字符串的中間)我試過: 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 可以具有不同的長度和值。

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

如果您只需要一個布爾值真/假答案,以確定lineVar是否存在於數組中的任何字符串中,請使用以下命令:

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

如果您需要索引,那就有點棘手了,因為它可能出現在數組的多個項目中。 如果你不是在尋找 bool,你能解釋一下你需要什么嗎?

老套:

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
}

如果您需要包含數組元素中子字符串的第一個元素的索引,您可以這樣做...

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 表達式來獲取包含子字符串的每個元素。

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

搜索結果的輸出:

歡迎來到聖何塞

歡迎來到舊金山

歡迎來到聖馬丁

這個字符串中間有 Welcome to San

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM