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

来源:这里教程网 时间:2026-02-21 16:33:15 作者:

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

相关推荐