C#應用正則斷定輸出能否為純數字、容器類。本站提示廣大學習愛好者:(C#應用正則斷定輸出能否為純數字、容器類)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用正則斷定輸出能否為純數字、容器類正文
容器類、正則表達式在簡直一切編程說話都存在的器械。很經常使用也很應用。上面用以下的一個掌握台小法式解釋C#的正則表達式與容器類的運用。
開端直接輸入在C#界說好的數據字典Dictionary,這就是Java與Python的HashMap,以後界說一個存int的List,讓用戶無窮輸出這個List的元素,輸出到#則停滯輸出,在輸出的進程中碰到不是純輸出,則謝絕這個輸出。
遍歷這個List輸入,以後應用C#的另外一個容器HashSet為這個List去重。

這個法式的代碼以下,其實以上一切的器械都在之前的文章說過。這重要是將這類思惟寫成C#說話罷了。
關於正則表達式可以參考:《js應用正則表達式磨練輸出內容能否為網址》
關於應用HashSet為List去重:《Java中ArrayList的應用辦法簡略引見》
using System;
using System.Collections.Generic;//用到了容器類
using System.Text.RegularExpressions;//用到了正則表達式
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("數據字典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("輸出#,停止輸出!");
Regex regex = new Regex("^[0-9]*$");
String input_string = "";
while (true)
{
Console.Write("請輸出數組的數字:");
input_string = Console.ReadLine();
if (input_string.Trim().CompareTo("#") == 0)
{
break;
}
else
{
if (regex.IsMatch(input_string))//應用正則表達式斷定能否輸出的是數字
{
list.Add(int.Parse(input_string));
}
else
{
Console.WriteLine("輸出的不是數字!請從新輸出!");
}
}
}
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();//期待用戶按回車才停止法式
}
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。