jordinho
jordinho
CC#
Created by jordinho on 9/9/2023 in #help
❔ Checking if a string only contains specified characters (Order doesn't matter)
I am trying to validate user input. My current approach is to iterate over every char of the input string and check wether the char has been specified. Is there any more efficient way?
class Navigation
{
public string Input { get; }

private List<char> _allowedCharacters { get; }

public Navigation()
{
AllowedCharacters = new List<char>()
{
'*', '/', '+', '-',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
}

public void UserInput()
{
bool invalidInput = true;

while (invalidInput)
{
Console.Write(">>> ");
Input = Console.ReadLine();

for (int i = 0; i < Input.Length; i++)
{
if (_allowedCharacters .Contains(Input[i]))
{
if (i == Input.Length - 1)
{
invalidInput = false;
break;
}
}
else
{
Console.WriteLine("Invalid\n");
invalidInput = true;
break;
}
}
}
}
}
class Navigation
{
public string Input { get; }

private List<char> _allowedCharacters { get; }

public Navigation()
{
AllowedCharacters = new List<char>()
{
'*', '/', '+', '-',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
}

public void UserInput()
{
bool invalidInput = true;

while (invalidInput)
{
Console.Write(">>> ");
Input = Console.ReadLine();

for (int i = 0; i < Input.Length; i++)
{
if (_allowedCharacters .Contains(Input[i]))
{
if (i == Input.Length - 1)
{
invalidInput = false;
break;
}
}
else
{
Console.WriteLine("Invalid\n");
invalidInput = true;
break;
}
}
}
}
}
41 replies