c# - 在 C# 中使用 LINQ 查找字符串数组中的确切子字符串

标签 c# arrays string linq substring

我正在尝试查看字符串数组中是否存在精确的子字符串。如果字符串中存在子字符串,则返回 true,但它将包含拼写错误。

编辑: 例如,如果我正在检查字符串数组中是否存在“Connecticut”,但拼写为“Connecticute”,它仍会返回 true,但我不希望它返回。我希望它为“Connecticute”返回 false 并为 仅限“康涅狄格州”

有没有办法使用 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))
...

关于c# - 在 C# 中使用 LINQ 查找字符串数组中的确切子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918022/

相关文章:

c - 实现 HTTP 1.0 服务器时出现的问题

c - 读取一个字符串,当找到换行符时将每个字符串存储到数组中

c# - 考虑时区的夏令时,将 UTC 日期时间转换为 future 时间

c# - ASP.NET MVC。如何禁用基于参数的必需验证?

c# - 处理存储过程

javascript - 在javascript中使用二维数组获得最高频率

c# - ASP MVC EF MultiSelect HTTP POST

c - C中的数组排序

c - C上的2D数组(初学者)

python - 在 Python 中从字符串转换为 boolean 值