检查是否有类似字符串
本文关键字:字符串 是否 检查 | 更新日期: 2023-09-27 17:50:52
我试图在文本中检查一个"错误"字符范围内的类似单词,而没有包含方法,因此:"cat" = *cat,c*at,ca*t,cat*。我的代码是。
下面是一个例子:
string s = "the cat is here with the cagt";
int count;
string[] words = s.Split(' ');
foreach (var item in words)
{
if(///check for "cat")
{
count++;
return count; (will return 2)
}
}
这将做你不想做的事,但我仍然认为SpellCheck库将是一种方式
string wordToFind = "cat";
string sentance = "the cat is here with the cagt";
int count = 0;
foreach (var word in sentance.Split(' '))
{
if (word.Equals(wordToFind, StringComparison.OrdinalIgnoreCase))
{
count++;
continue;
}
foreach (var chr in word)
{
if (word.Replace(chr.ToString(), "").Equals(wordToFind, StringComparison.OrdinalIgnoreCase))
{
count++;
}
}
}
// returns 2
Regexp可能是最好的解决方案。但是也可以试试这个
String str = yourstring;
String s1 = 'cat';
int cat1 = yourstring.IndexOf(s1,0);
也许,您可以使用正则表达式来查找匹配。
Regex Class MSDN
c# Regex30分钟正则表达式教程
这是简单和正确的,但慢:
static bool EqualsExceptOneExtraChar(string goodStr, string strWithOneExtraChar)
{
if (strWithOneExtraChar.Length != goodStr.Length + 1)
return false;
for (int i = 0; i < strWithOneExtraChar.Length; ++i)
{
if (strWithOneExtraChar.Remove(i, 1) == goodStr)
return true;
}
return false;
}