C#程序检查字符串是否包含特殊字符

C#程序检查字符串是否包含特殊字符

要检查字符串是否包含特殊字符,您需要使用以下方法 -

Char.IsLetterOrDigit

登录后复制

在 for 循环中使用它并检查是否包含特殊字符的字符串。

假设我们的字符串是 -

string str = "Amit$#%";

登录后复制

现在将字符串转换为字符数组 -

str.ToCharArray();

登录后复制

使用 for 循环并使用 isLetterOrDigit() 方法检查每个字符。

示例

让我们看看完整的代码。

现场演示

using System;
namespace Demo {
class myApplication {
static void Main(string[] args) {
string str = "Amit$#%";
char[] one = str.ToCharArray();
char[] two = new char[one.Length];
int c = 0;
for (int i = 0; i < one.Length; i++) {
if (!Char.IsLetterOrDigit(one[i])) {
two[c] = one[i];
c++;
}
}
Array.Resize(ref two, c);
Console.WriteLine("Following are the special characters:");
foreach(var items in two) {
Console.WriteLine(items);
}
Console.ReadLine();
}
}
}

登录后复制

输出

Following are the special characters:
$
#
%

登录后复制

以上就是C#程序检查字符串是否包含特殊字符的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!