【问题标题】:Comparing two string in c#c#中比较两个字符串
【发布时间】:2013-03-18 18:53:30
【问题描述】:

我有一个程序需要将任何给定的字符串与预定义的字符串进行比较,并确定是否发生了插入错误、删除错误、转置或替换错误。

例如,如果向用户展示了dog这个词并且用户提交了dogsdoge,它应该通知用户出现插入错误。

我该怎么做?

【问题讨论】:

  • 在哪里插入数据库?
  • 谢谢。但我没有使用数据库。
  • 并且预定义的字符串会不断变化吗?还是恒定的?
  • “插入错误、删除错误、转置或替换错误”是什么意思?请提供示例。
  • 这很可能是如何实现Levenshtein distance 问题的许多重复之一。 - 在stackoverflow.com/…选择你的

标签: c# .net string


【解决方案1】:

您可能需要为每个单独的错误类型编写一个方法来查看它是否是错误,例如:

bool IsInsertionError(string expected, string actual) {
    // Maybe look at all of the chars in expected, to see if all of them
    // are there in actual, in the correct order, but there's an additional one
}

bool IsDeletionError(string expected, string actual) {
    // Do the reverse of IsInsertionError - see if all the letters
    // of actual are in expected, in the correct order,
    // but there's an additional one
}

bool IsTransposition(string expected, string actual) {
    // This one might be a little tricker - maybe loop through all the chars,
    // and if expected[i] != actual[i], check to see if 
    // expected[i+1] = actual[i] and actual[i-1]=expected[i]
    // or something like that
}

一旦你构建了所有单独的规则,并且你首先检查了规则的相等性,一次触发它们中的每一个。

你必须把这样的问题分解成小部分,然后一旦你有一堆简单的问题,一次解决一个。

【讨论】:

    【解决方案2】:

    在我的脑海中,但我认为这应该让你开始:

    InsertionDeletion 应该很简单;只需检查字符串的长度。

    if(originalString.Length > newString.Length) 
    {
        //deletion
    }
    else if(originalString.Length < newString.Length)
    {
        //insertion
    }
    

    要检测transposition,请检查长度是否匹配,如果匹配,您可以从两个字符串创建两个List&lt;char&gt;。然后使用下面的表达式检查它们是否匹配

    bool isTransposed = originalList.OrderBy(x => x).SequenceEquals(newList.OrderBy(y => y));
    

    要检测substitution,您可以使用Hamming Distance 并检查它是否大于0。

    【讨论】:

      【解决方案3】:

      我建议您创建一个function,它将parameter 作为input stingfunction 看起来或多或少像这样。然后在任何你想要的地方使用function

      private void CheckString(string userString)
      {
          string predefinedString = "dog";
          if (userString == predefinedString)
          {
              // write your logic here
          }
          else
          {
              MessageBox.Show("Incorrect word"); // notify the users about incorrect word over here
          }
      }
      

      【讨论】:

      • 这只告诉字符串是否相等。 OP想要区分插入错误,如“dog”的“doge”和其他类型的错误,如交换两个连续字符的“dgo”。我确定 OP 已经知道 "==" 运算符。
      • 其实这就是OP问题的答案;问题是 OP 问题没有给我们足够的信息来回答。 @KeithThompson,您实际上是在假设 OP 想要什么。
      • @AnthonyNichols - OP 希望算法能够检测转座、替换、插入或删除。我同意问题中没有提供足够的信息,但很明显,OP 想要的不仅仅是检查两个字符串是否匹配(否则插入/删除等方面不需要提及)
      • @AnthonyNichols:OP 在区分插入、删除、转座和替换错误方面非常具体。
      • @KeithThompson OPs 示例另有说明。我跟着他给出的例子去了。不过没关系。
      猜你喜欢
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2015-11-13
      相关资源
      最近更新 更多