C#利用正則判斷輸入是否為純數(shù)字、容器類
容器類、正則表達(dá)式在幾乎所有編程語言都存在的東西。很常用也很使用。下面用如下的一個控制臺小程序說明C#的正則表達(dá)式與容器類的應(yīng)用。
開始直接輸出在C#定義好的數(shù)據(jù)字典Dictionary,這就是Java與Python的HashMap,之后定義一個存int的List,讓用戶無限輸入這個List的元素,輸入到#則停止輸入,在輸入的過程中遇到不是純輸入,則拒絕這個輸入。
遍歷這個List輸出,之后利用C#的另一個容器HashSet為這個List去重。
這個程序的代碼如下,其實以上所有的東西都在以前的文章說過。這主要是將這種思想寫成C#語言而已。
關(guān)于正則表達(dá)式可以參考:《js利用正則表達(dá)式檢驗輸入內(nèi)容是否為網(wǎng)址》
關(guān)于利用HashSet為List去重:《Java中ArrayList的使用方法簡單介紹》
using System; using System.Collections.Generic;//用到了容器類 using System.Text.RegularExpressions;//用到了正則表達(dá)式 class Collections { //C#容器Dictionary的基本使用 public static void dictionaryTest() { Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("K1", 123); dict["K2"] = 456; dict.Add("K3", 789); Console.WriteLine("數(shù)據(jù)字典dict中的Key-value對為:"); foreach (KeyValuePair<string, int> k in dict) { Console.WriteLine("{0}-{1}; ", k.Key, k.Value); //K1-123; K2-456; K3-789; } } //C#容器List與HashSet的基本使用 public static void listTest() { List<int> list = new List<int>(); Console.WriteLine("輸入#,結(jié)束輸入!"); Regex regex = new Regex("^[0-9]*$"); String input_string = ""; while (true) { Console.Write("請輸入數(shù)組的數(shù)字:"); input_string = Console.ReadLine(); if (input_string.Trim().CompareTo("#") == 0) { break; } else { if (regex.IsMatch(input_string))//利用正則表達(dá)式判斷是否輸入的是數(shù)字 { list.Add(int.Parse(input_string)); } else { Console.WriteLine("輸入的不是數(shù)字!請重新輸入!"); } } } Console.WriteLine("輸入的List為:"); for (int i = 0; i < list.Count; i++) { Console.Write(list[i] + " "); } Console.WriteLine(); list = new List<int>(new HashSet<int>(list));//利用集合為list去重 Console.WriteLine("List利用Set去重后為:"); for (int i = 0; i < list.Count; i++) { Console.Write(list[i] + " "); } Console.WriteLine(); ; } public static void Main(String[] args) { dictionaryTest(); listTest(); Console.ReadKey();//等待用戶按回車才結(jié)束程序 } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實現(xiàn)百度網(wǎng)站收錄和排名查詢功能思路及實例
這篇文章主要介紹了C#實現(xiàn)百度網(wǎng)站收錄和排名查詢功能思路及實例,本文思路同樣適用必應(yīng)、搜狗、搜搜、360等搜索引擎,需要的朋友可以參考下2015-01-01C#使用ToUpper()與ToLower()方法將字符串進(jìn)行大小寫轉(zhuǎn)換的方法
這篇文章主要介紹了C#使用ToUpper()與ToLower()方法將字符串進(jìn)行大小寫轉(zhuǎn)換的方法,實例分析了C#大小寫轉(zhuǎn)換的相關(guān)技巧,需要的朋友可以參考下2015-04-04