gpt4 book ai didi

C# 烦恼 - 在 sting 之外访问数据

转载 作者:行者123 更新时间:2023-11-30 16:18:58 25 4
gpt4 key购买 nike

我用C#做了一个邮件验证程序,但是如何检查字符串以外的数据呢?

这是我的 C# 代码:

private bool CheckEmail()
{
string email1 = email.Text;

//calculating the length of the email
int EmailLen = email1.Length;
int num = 0;

//the first character of the email must not be the "@"
if (email1.Substring(0, 1) != "@")
{
//checking the email entered after the first character as it is not a "@" so i will start from 1.
for (int i = 1; i < EmailLen; i++)
{
//prevents there from being two "@"next to each other
if (email1[i] == '@' && (i + 1) < email1.Length && email1[i + 1] != '@')
{
//if there is an "@" in the email then num will increase by one
num = num + 1;

//now the stored value of i is the position where the "@" is placed. j will be i+2 as there should be at least one character after the "@"
int j = i + 2;
if (j < EmailLen)
{
for (int k = j; k < EmailLen; k++)
{
//when it finds a "." In the email, the character after the "." Should not be empty or have a space, e.g. it should be something like ".com"

if (email1[k] == '.' && k + 1 < email1.Length && email1[k + 1] != ' ')
{
num = num + 1;
}
}
}
else
{
break;
}
}
}
}
else
{
num = 0;
}

//if the num is 2, then the email is valid, otherwise it is invalid. If the email had more than one "@" for example, the num will be greater than 2.

if (num == 2)
{
return true;
}
else
{
return false;
}
}

当我尝试输入“aa@”时,出现此错误:“索引和长度必须引用字符串中的某个位置。”

enter image description here

当我键入 aa@a 时。 ,我收到此错误:“索引和长度必须引用字符串中的位置。”

enter image description here

最佳答案

您不能访问字符串之外的数据。这是有充分理由的 - 这样做会违反类型安全,而类型安全是 .NET CLR 等虚拟机的主要吸引力。

您只想检查您的边界以确保您没有尝试访问不存在的字符串部分。顺便说一句,为了检查单个字符,你完全想做 email1[i],而不是 email1.Substring(i, 1),所以你不会构造新的字符串左侧、右侧和中心的对象。

你的第一个测试应该是:

if (email1[i] == '@' && i + 1 < email1.Length && email1[i + 1] != '@')

关于C# 烦恼 - 在 sting 之外访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15624424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com