IndexOf identifies illegal strings and is simple and easy to understand.
renderings
Illegal characters in the string can be identified and displayed.
Implement code
private string UnlegalString(string str)//过滤非法字符串
{
//制定出非法字符串
string Unlegalstr = "-_*×――(^)$%~!/@#$…&%¥—+=<>《》|!!???::•`·、。,;,.;\"‘’“”-]";
//存储提示用户应该修改的文本
string UserMsg = "";
//计数结果
int res = -1;
//根据用户输入长度循环
for (int i = 0; i < str.Length; i++)
{
res=Unlegalstr.IndexOf(str[i]);//若是没有则会返回-1
if (res != -1)//如果不等-1,证明有结果
{
UserMsg += str[i].ToString();//存储结果并返回
}
}
if (res > 0)
return UserMsg;//返回非法字符串
else
return "";//没有则不返回
}
transfer
private void button1_Click(object sender, EventArgs e)//Button_Click的方法中
{
//调用上面的方法,上面方法返回是字符串,这里判断一下是不是返回来空的。
if (UnlegalString(textBox1.Text) != "")
{
//获取非法字符串
string str = UnlegalString(textBox1.Text);
MessageBox.Show($"存在非法字符串“{str}”!请修改!", "提示");
}
else
{
MessageBox.Show("不存在非法字符串", "提示");
}
}
Expand the methods res=Unlegalstr.IndexOf(str[i]);
used IndexOf
.
String.IndexOf method
- Refer to official documentation.
definition
-
Namespaces:
-
Assembly:
System.Runtime.dll
Reports the zero-based index of the first occurrence of the specified Unicode character or string in this instance. This method returns -1 if the character or string is not found in this instance .