检查类似的字符串

时间:2013-01-06 07:46:11

标签: c# string

我正在尝试在一个文本中查找一个“错误”字符范围内的类似单词而没有包含方法,以便:“cat”= * cat,c * at,ca * T,猫*。我的代码是。

以下是一个例子:

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)
    }
}

4 个答案:

答案 0 :(得分:1)

这会做你想要的,但我仍然认为拼写检查库将是你的方式

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

答案 1 :(得分:0)

Regexp可能是最好的解决方案。但也要尝试一下。

String str = yourstring;
String s1 = 'cat';
 int cat1 = yourstring.IndexOf(s1,0); 

答案 2 :(得分:0)

可能您可以使用正则表达式进行查找匹配。

Regex Class MSDN

C# Regex

The 30 Minute Regex Tutorial

答案 3 :(得分:0)

这很简单也很正确但很慢:

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;
}
相关问题