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

csharpserver side programmingprogramming更新于 2025/9/24 11:47:00

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

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:
$
#
%

相关文章