用於檢查字串是否包含任何特殊字元的 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:
$
#
%

更新於:2020 年 6 月 19 日

10K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告