Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find exact substring in string array using LINQ in C#

I'm trying to see if an exact substring exists in a string array. It is returning true if the substring exists in the string but it will contains spelling errors.

EDIT: For example if I am checking if 'Connecticut' exists in the string array but it is spelled 'Connecticute' it will still return true but I do not want it to. I want it to return false for 'Connecticute' and return true for 'Connecticut' only

Is there a way to do this using 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();
            }
        }
    }
}
  }
like image 768
user3394486 Avatar asked May 06 '26 19:05

user3394486


2 Answers

String.Contains returns true if one part of the string is anywhere within the string being matched.

Hence "Conneticute".Contains("Conneticut") will be true.

If you want exact matches, what you're looking for is String.Equals

...
if (states.Any(s.Equals))
...
like image 82
Jamiec Avatar answered May 09 '26 09:05

Jamiec


You could use \b to match word breaking characters (ie. white spaces, periods, start or end of string etc):

  var r = new Regex("\bConneticut\b", RegexOptions.IgnoreCase);
  var m = r.Match("Conneticute");
  Console.WriteLine(m.Success); // false
like image 21
Mike Chamberlain Avatar answered May 09 '26 07:05

Mike Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!