簡體   English   中英

在C#中使用LINQ在字符串數組中查找確切的子字符串

[英]Find exact substring in string array using LINQ in C#

我正在嘗試查看字符串數組中是否存在確切的子字符串。 如果子字符串存在於字符串中,它將返回true,但它將包含拼寫錯誤。

編輯:例如,如果我正在檢查字符串數組中是否存在“ Connecticut ”,但拼寫為“ Connecticute ”,它仍然會返回true,但我不想這樣做。 我希望它為'Connecticute'返回false並且僅為'Connecticut'返回true

有沒有辦法用LINQ做到這一點?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {
        string[] sample = File.ReadAllLines(@"C:\samplefile.txt");
        /* Sample file containing data organised like
        Niall      Gleeson      123 Fake Street     UNIT 63     Connecticute     00703       USA      
         */

        string[] states = File.ReadAllLines(@"C:\states.txt"); //Text file containing list of all US states
        foreach (string s in sample)
        {
            if (states.Any(s.Contains))
            {
                Console.WriteLine("Found State");
                Console.WriteLine(s);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Could not find State");
                Console.WriteLine(s);
                Console.ReadLine();
            }
        }
    }
}
  }

如果字符串的一部分在匹配的字符串中的任何位置,則String.Contains返回true。

因此"Conneticute".Contains("Conneticut")將是真的。

如果你想要完全匹配,你要找的是String.Equals

...
if (states.Any(s.Equals))
...

您可以使用\\b匹配分符號(即。空格,句點,字符串的開頭或結尾等):

  var r = new Regex("\bConneticut\b", RegexOptions.IgnoreCase);
  var m = r.Match("Conneticute");
  Console.WriteLine(m.Success); // false

而不是使用string.Contains ,它匹配字符串是否包含字母序列,而是使用正則表達式匹配,以及您認為合適的任何內容。 例如,這將匹配單詞邊界,

var x = new [] { "Connect", "Connecticute is a cute place", "Connecticut", "Connecticut is a nice place" };
x.Dump();
var p = new Regex(@"\bConnecticut\b", RegexOptions.Compiled);
x.Where(s=>p.IsMatch(s)).Dump();

這將匹配“康涅狄格”和“CConnecticut是一個不錯的地方”,但不是其他字符串。 更改正則表達式以滿足您的確切要求。

(。dump()用於linqpad ,可以用來試驗這種事情)

暫無
暫無

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

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