我已经制作了一个函数,如果它们站在我的列表中,它可以替换字符的位置
代码:
public string NoSimilarChar(string password)
{
var listOfSimilarCharacters = new Dictionary<string, string>();
listOfSimilarCharacters.Add("l", "i");
listOfSimilarCharacters.Add("1", "i");
listOfSimilarCharacters.Add("O", "0");
// Iterate through each character
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i].ToString();
// check if the current char exists in either the key or the value of the list of similar characters
if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
}
}
return password;
}
现在我想知道如何在删除字符时加载NoSimilarChar函数
我认为是这样的: if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
NoSimilarChar(password);
}
但我觉得这不好,因为他会停留在循环中。
答案 0 :(得分:0)
///for replacing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
password = password.Replace(item.Key, item.Value);
}
///for removing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
if (password.IndexOf(item.Key) >= 0)
password = password.Remove(password.IndexOf(item.Key), 1);
}
答案 1 :(得分:0)
尝试这个更简单的
var charsThatCannotbeinUserPwd = new[] {'1', 'l', 'O', '0', 'i'};
// Iterate through each character
var builder = new StringBuilder();
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i];
if (!charsThatCannotbeinUserPwd.Any(x => x.Equals(currentCharacter)))
builder.Append(currentCharacter);
}
return builder.ToString();
答案 2 :(得分:0)
您好像要从密码中删除一组字符。如果是这种情况,那么您不需要使用Dictionary
。如果您想要将一个字符替换为另一个字符,Dictionary
会更有意义。此外,您不需要在此处使用递归。我相信你需要的只是一个你要删除的字符数组和一个简单的循环来删除它们。
public string NoSimilarChar(string password)
{
string[] charsToRemove = new string[] { "l", "i", "1", "0", "O" }
foreach (string charToRemove in charsToRemove)
{
password = password.Replace(charToRemove, "");
}
return password;
}
仅供参考:我已将字符数组定义为字符串,因为您需要用空字符串替换该字符,并且没有空字符。