C# 检查类似字符串

C# 检查类似字符串,c#,string,C#,String,我试图在文本中检查一个“错误”字符范围内的类似单词,而不使用contain方法,因此:“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++;

我试图在文本中检查一个“错误”字符范围内的类似单词,而不使用contain方法,因此:“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)
    }
}

Regexp可能是最好的解决方案。但是也试试这个

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

也许,您可以使用正则表达式来查找匹配项


这将做你不想做的事,但我仍然认为拼写检查库将是一个不错的选择

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

这很简单、正确,但速度很慢:

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;
}
静态bool equalexceptoneextrachar(字符串goodStr,字符串strWithOneExtraChar)
{
if(strWithOneExtraChar.Length!=goodStr.Length+1)
返回false;
对于(int i=0;i
定义“相似”。这句话:“cat”=gcat,cgat,cagt,catg。”告诉我,对你来说,“相似”意味着“一个词中的g不合适”。您是否正在尝试实现拼写检查器?有比检查单词的每一个可能的排列更优雅的方法,比如如果有一个字符丢失了怎么办,比如在
cat
->
at
?“g”只是一个例子。。。可以是任何一封信。如果缺少一个字符,则不好。:)为什么不使用contains方法。。?你真正想要完成的是什么。。?你的代码也没有意义你要对照什么检查。。?一个字符还是一个单词?@zipo#u-soft:我的观点是这样的。四个例子中有两个失败。tnx,我已经试过了:),但我不想使用c#内置方法。zipo#u-soft你想做什么。。也许你不想使用内置的方法,因为你不知道如何使用它们。。这是一个家庭作业吗?我不明白为什么我们不想使用语言的内置函数却要使用它-(@EdS.你能告诉我它失败的地方吗?阿普改变了他的字符串…邦科迪戈,这篇文章应该被关闭..我+1你的反对票顺便说一句,因为阿普自己不知道他想要什么,他无法解释他想用他的代码做什么其他平台..他不知道如何使用拼写检查库,因为他本可以这么做这使用了几行使用正则表达式的代码,但他不想使用C#.NET框架提供的内置函数或方法是的,这是我能想到的最小数量的“内置”函数,哈哈,我应该在一个可笑的Linq状态中完成:)实际上你应该这样做会让他头晕目眩。。此帖子应关闭。。这真的是浪费时间,如果将来有人需要同样的东西,对他们也没有帮助。。你的代码正是我要发布的,但在意识到OP不需要真正的帮助后,我不会泄露明显的东西,这是在做一个嵌套的foreach..lol