如何调用函数

本文关键字:函数 调用 何调用 | 更新日期: 2023-09-27 18:02:10

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

代码:

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

但我认为这是不好的,因为他会留在一个循环

如何调用函数

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

试试这个更简单的

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

看起来您想要从密码中删除一组字符。如果是这样的话,你就不需要使用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;
}

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