我正在尝试查看字符串数组中是否存在精确的子字符串。如果字符串中存在子字符串,则返回 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/