多次比较字符串

本文关键字:字符串 比较 | 更新日期: 2023-09-27 18:02:11

我正在生成随机脚本,但我必须保证每个新脚本都是唯一的(以前没有重复过)。所以基本上每个已经生成的脚本都会与每个新脚本进行比较。

而不是仅仅使用正常的字符串比较,我认为必须有一种方法来散列每个新脚本,以便比较会更快。

关于如何散列字符串使多个比较更快的想法?

多次比较字符串

一种方法是使用HashSet<String>

hashset类提供了高性能的集合操作。集合是不包含重复元素的集合,其元素没有特别的顺序。

HashSet<string> scripts = new HashSet<string>();
string generated_script = "some_text";
if (!scripts.Contains(generated_script)) // is HashSet<String> dont contains your string already then you can add it
{
    scripts.Add(generated_script);
}

还可以检查数组中是否存在duplicate items。但与HashSet<String>

相比,这可能不是很有效
string[] array = new[] {"demo", "demo", "demo"};
string compareWith = "demo";
int duplicates_count = array.GroupBy(x => x).Count(g => g.Count() > 1);

使用下面的HashSet

        string uniqueCode= "ABC";
        string uniqueCode1 = "XYZ";
        string uniqueCode2 = "ABC";
        HashSet<string> uniqueList = new HashSet<string>();
       uniqueList.Add(uniqueCode);
       uniqueList.Add(uniqueCode1);
       uniqueList.Add(uniqueCode2);

如果你看到Countunique 你将所以ABC不会出现两次

您可以使用HashSet。哈希集保证不包含重复项

将脚本与其散列一起存储:

class ScriptData
{
  public ScriptData(string script)
  {
    this.ScriptHash=script.GetHashCode();
    this.Script=script;
  }
  public int ScriptHash{get;private set;}
  public string Script{get;private set;}
}

然后,每当您需要检查新的随机脚本是否唯一时,只需使用新脚本的哈希码并搜索所有具有相同哈希码的ScriptData实例。如果你没有找到任何你知道你的新随机脚本是唯一的。如果你确实发现了一些,那么它们可能是相同的,你必须比较脚本的实际文本,以查看它们是否相同。

您可以将每个生成的string存储在HashSet中。

对于每个新的字符串,你将调用方法Contains,它以0(1)复杂度运行。这是确定新生成的字符串是否以前生成过的一种简单方法。