0

我做了一个函数,如果它们站在我的列表中,它可以替换字符的位置

代码:

   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);
                }

但我认为这不好,因为他会一直处于循环状态。

4

3 回答 3

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();
于 2013-03-04T11:24:28.950 回答
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);
  }
于 2013-03-04T11:18:52.387 回答
0

看起来您想从密码中删除一组字符。如果是这种情况,那么您不需要使用Dictionary. 如果您想用另一个字符替换一个字符, ADictionary会更有意义。此外,您不需要在这里使用递归。我相信您只需要一个要删除的字符数组和一个简单的循环即可删除它们。

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;
}

仅供参考:我已将字符数组定义为字符串,因为您希望将字符替换为空字符串并且没有空字符。

于 2013-03-04T11:34:44.883 回答