C# 严格检查一个字符串中的所有字符是否存在于另一个字符串中(NO LINQ)



我有一本字典,我想删除所有以某种方式包含给定单词所有字符的键。例如,如果给定的字被破坏,则所有具有诸如";"中断"co2rupt"ruptor";应移除。

到目前为止,我有以下代码,但它似乎不起作用,我不知道为什么。

static Dictionary<string,double> Dict2(){
var dict = new Dictionary < string, double > ();
dict.Add("rupt cor0",1);
dict.Add("cor rupt1", 33);
dict.Add(" 4 cor ru pt4", 10752);
dict.Add("ted45", 6.878);
dict.Add("key2", 0.0033482143);
var word = "corrupt";
Console.WriteLine("This is the origina dictionary");
foreach (KeyValuePair<string, double> kvp in dict)
{
Console.WriteLine($"Key {kvp.Key}: Value={kvp.Value}");
}

foreach (KeyValuePair<string, double> entry in dict)
{

foreach (char character in word)
{
if (entry.Key.Contains(character))
{
dict.Remove(entry.Key);
}

}

}

这个代码应该删除前3对,但当我删除对后重新打印dict时,它只包含key2:00033482143。

我想要一种不使用LINQ的方式。

一种方法是循环遍历所有键,如果键长度至少与单词一样长,则循环遍历单词的每个字符并将其从键中删除。然后,如果我们已经删除了所有字符,那么这个键应该被删除,因为它包含了所有字符。这需要创建一个临时变量来存储关键字和单词值,因为我们不想修改原始值。

var keysToRemove = new List<string>();
foreach (var key in dict.Keys)
{
if (key.Length < word.Length) continue;
var tmpKey = key;
var tmpWord = word;
foreach (var chr in word)
{
var keyIndex = tmpKey.IndexOf(chr);
if (keyIndex < 0) break;
tmpKey = tmpKey.Remove(keyIndex, 1);
tmpWord = tmpWord.Remove(0, 1);
}
if (tmpWord.Length == 0) keysToRemove.Add(key);
}
foreach (var keyToRemove in keysToRemove)
{
dict.Remove(keyToRemove);
}

由于corruptted45
中的匹配t,因此应该删除第四个元素。此外,您应该以相反的顺序对正在修改的列表进行迭代。

var dict = new Dictionary<string, double>();
dict.Add("rupt cor0", 1);
dict.Add("cor rupt1", 33);
dict.Add(" 4 cor ru pt4", 10752);
dict.Add("ted45", 6.878);
dict.Add("key2", 0.0033482143);
var word = "corrupt";
Console.WriteLine("This is the origina dictionary");
foreach (KeyValuePair<string, double> kvp in dict)
{
Console.WriteLine($"Key {kvp.Key}: Value={kvp.Value}");
}

for (int i = dict.Keys.Count - 1; i >= 0; i--)
{
var entry = dict.ElementAt(i);
foreach (char character in word)
{
if (entry.Key.Contains(character))
{
Console.WriteLine($"Entry `{entry.Key}` contains `{character}`. Remove");
dict.Remove(entry.Key);
break;
}
}
}
Console.WriteLine("This is the modified dictionary");
foreach (KeyValuePair<string, double> kvp in dict)
{
Console.WriteLine($"Key {kvp.Key}: Value={kvp.Value}");
}

最新更新