[英]How can I loop through a string entered by a user in C#?
Now I am trying to check for correct format in this ID number entered by the user in this program.现在我正在尝试检查用户在此程序中输入的此 ID 号的格式是否正确。 Now I am aware of the match case, but I'm trying to avoid doing that.现在我知道匹配案例,但我试图避免这样做。 I was considering a foreach loop, but the ID is in XX-9999 format and I don't know how to check different data types in that kind of loop.我正在考虑一个 foreach 循环,但 ID 是 XX-9999 格式,我不知道如何在这种循环中检查不同的数据类型。
I tried to use a for loop because my thinking was since a string is just an array of characters, that I can treat it as such.我尝试使用 for 循环,因为我的想法是因为字符串只是一个字符数组,我可以这样对待它。 But I think that my index is being checked instead of the string characters.但我认为正在检查我的索引而不是字符串字符。
Either way, here is my method:无论哪种方式,这是我的方法:
public bool Validate_Employee_ID()
{
const int VALID_LENGTH = 7; // Length of a valid string
bool valid = true; // Flag to indicate validity
string strEmployeeID = txtEmployeeID.Text.Trim(); // get trimmed string from txtEmployeeID
string[] stringEmpIDSplit = strEmployeeID.Split('-');
if (strEmployeeID.Length == VALID_LENGTH)
{
// Check the first two characters in string.
for (int i = 0; i <= strEmployeeID[1]; i++)
{
// if the character is not a letter, valid equals false
if (!char.IsLetter(strEmployeeID[i]) == true)
{
MessageBox.Show("1) The employee ID must be in the following format: XX-9999.", "Entry Check", MessageBoxButton.OK, MessageBoxImage.Information);
txtEmployeeID.Focus();
// first two chars are not letters
valid = false;
return valid;
}
}
// Check the rest of the string to check the format.
for (int j = strEmployeeID[3]; j <= strEmployeeID[6]; j++)
{
// if the character is not a letter, valid equals false
if (!char.IsDigit(strEmployeeID[j]) == true)
{
MessageBox.Show("2) The employee ID must be in the following format: XX-9999.", "Entry Check", MessageBoxButton.OK, MessageBoxImage.Information);
txtEmployeeID.Focus();
// last 4 chars are not numbers
valid = false;
return valid;
}
}
}
else valid = true;
return valid;
}
In this case you don't really need a for
loop since we have the All
method from System.Linq
which can help us check if all characters in a string meet some criteria:在这种情况下,您实际上并不需要for
循环,因为我们有来自System.Linq
的All
方法,它可以帮助我们检查字符串中的所有字符是否符合某些条件:
const int validLength = 7; // Length of a valid string
var employeeID = txtEmployeeID.Text.Trim(); // Get trimmed string from txtEmployeeID
var empIDSplit = employeeID.Split('-'); // Split on the dash character
if (employeeID.Length != validLength || // Validate overall length
empIDSplit.Length != 2 || // Validate number of parts after split
empIDSplit[0].Length != 2 || // Validate first part length
empIDSplit[1].Length != 4 || // Validate second part length
!empIDSplit[0].All(char.IsLetter) || // Validate first part are letters
!empIDSplit[1].All(char.IsDigit) // Validate second part are digits
)
{
MessageBox.Show("1) The employee ID must be in the following format: XX-9999.",
"Entry Check", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtEmployeeID.Focus();
return false;
}
return true;
If you do find yourself needing to use a for
loop, along with a variable to track the validation result, here's a way to do that.如果您确实发现自己需要使用for
循环以及一个变量来跟踪验证结果,这里有一种方法可以做到这一点。 We start with the assumption that the input is valid, and then we "fail fast" if we find that it's not.我们首先假设输入是有效的,然后如果我们发现它不是,我们就会“快速失败”。
When we find invalid data, we set the variable to false and then skip to the end of the method, where we display our message (if needed) and return the result:当我们发现无效数据时,我们将变量设置为 false,然后跳到方法的末尾,在那里我们显示我们的消息(如果需要)并返回结果:
public bool Validate_Employee_ID()
{
const int validLength = 7; // Length of a valid string
var isValid = true; // Validation result
var employeeID = txtEmployeeID.Text.Trim(); // Trimmed string from txtEmployeeID
var empIDSplit = employeeID.Split('-'); // Split on the dash character
if (employeeID.Length != validLength || // Validate overall length
empIDSplit.Length != 2 || // Validate number of parts after split
empIDSplit[0].Length != 2 || // Validate first part length
empIDSplit[1].Length != 4) // Validate second part length
{
isValid = false;
}
else
{
foreach (var chr in empIDSplit[0])
{
if (!char.IsLetter(chr))
{
isValid = false;
break; // "Fail fast" by exiting the loop at the first bad data
}
}
// "Fail fast" by not checking the second part if the first one failed
if (isValid)
{
foreach (var chr in empIDSplit[1])
{
if (!char.IsDigit(chr))
{
isValid = false;
break; // "Fail fast" by exiting the loop at the first bad data
}
}
}
}
// Display an error message if the input was invalid
if (!isValid)
{
MessageBox.Show("1) The employee ID must be in the following format: XX-9999.",
"Entry Check", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtEmployeeID.Focus();
}
return isValid;
}
You're confusing your index for your characters你混淆了你的角色索引
// Check the rest of the string to check the format.
for (int j = 3; j <= 6; j++)
{
// if the character is not a letter, valid equals false
if (!char.IsDigit(strEmployeeID[j]))
{
//snip
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.